Java Reference
In-Depth Information
Drawing with Canvas
The canvas element was introduced to allow graphics to be drawn onto a web page in real
time using JavaScript. A canvas element is a rectangular element on the web page. It has
a coordinate system that starts at (0,0) in the top-left corner. To add a canvas element to a
page, the <canvas> tag is used specifying a height and width . Anything placed inside
the tag will only display if the canvas element is unsupported:
<canvas id="canvas" width="200" height="100">Sorry, but
your
browswer does not support the canvas element</canvas>
This canvas can now be accessed in a JavaScript program using the docu-
ment.getElementById() method:
var canvas = document.getElementById("canvas");
The next step is to access the context of the canvas. This is an object that contains all the
methods used to draw onto the canvas. At the moment there's only a two-dimensional con-
text, although there are plans to implement a three-dimensional context in the future. The
getContext() method is used to access the context:
var context = canvas.getContext("2d");
Now we have a reference to the context, we can access its methods and draw onto the can-
vas. The fill and stroke colors can be changed by assigning a CSS color to the fillStyle
and strokeStyle properties respectively:
context.fillStyle = "#0000cc"; // a blue fill color
context.strokeStyle = "#ccc"; // a gray stroke color
These colors will be utilized for everything that's drawn onto the canvas until they're
changed.
The lineWidth property can be used to set the width of any line strokes drawn onto the
canvas. It defaults to one pixel and remains the same until it's changed:
Search WWH ::




Custom Search