Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Filling and drawing boxes

2010-10-21

The HTML5 canvas is an excellent way to display vector graphics on the web, that is, images that isn’t made up by pixels, but geometrical shapes, such as lines and boxes. To display a vector image, you will need a canvas tag that defines the size of the image, and some JavaScript code that defines the picture content. This will create a 400×300 pixel image. The ID attribute is used to access the canvas from your script.

<canvas id="myCanvas" width="400" height="300"></canvas>

The JavaScript code that you write, is suitable to call from the onLoad event of your page, like so:

<html>
   <head>
      <script language="javascript">
         function doSomeDrawing(){
         }
      </script>
   </head>
   <body onload="doSomeDrawing();">
      <canvas id="myCanvas" width="400" height="300"></canvas>
   </body>
</html>

The rest of what you see, takes place from within the doSomeDrawing function. First off, acquire the references you need.

//Get a reference to the canvas element.
var myCanvas=document.getElementById("myCanvas");
            
//Get a reference to the graphics context object.
var g=myCanvas.getContext();

The rest of this example, will use the graphics context object (the g reference). Now, the fillStyle property will control how shapes are filled. Assigning null to the fillStyle property will prevent filling all together. Likewise, the strokeStyle property will control how shape outlines are stroked, and assigning null will prevent outlines. In some cases, as with the rectangle, the name of the method tells if the shape will be stroked or filled. The following code will do a red outline and an overlapping green filled rectangle:

//Get a reference to the canvas element.
var myCanvas=document.getElementById("myCanvas");

//Get a reference to the graphics context object.
var g=myCanvas.getContext("2d");

g.strokeStyle="#ff0000";
g.strokeRect(10, 10, 100, 100);

g.fillStyle="#00ff00";
g.fillRect(30, 30, 100, 100);

And this is the result:

Categories: General

Tags: HTML5

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips