HTML and CSS Reference
In-Depth Information
<canvas id="canvas" width="300" height="300">
<strong>
Canvas Supporting Browser Required
</strong>
</canvas>
Note the alternative content placed within the element for browsers that don't support
the element.
After you place a
<canvas>
tag in a document, your next step is to use JavaScript to
access and draw on the element. For example, the following fetches the object by its
id
value and creates a two-dimensional drawing context:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
N
OTE
3D drawing is coming to
<canvas>
but is not currently defined outside of extensions.
Once you have the drawing context, you might employ various methods to draw on it.
For example, the
strokeRect(
x
,
y
,
width
,
height
)
method takes
x
and
y
coordinates and
height
and
width
, all specified as numbers representing pixels. For example,
context.strokeRect(10,10,150,50);
would draw a simple rectangle of 150 pixels by 50 pixels starting at the coordinate 10,10
from the origin of the placed
<canvas>
tag. If you wanted to set a particular color for the
stroke, you might set it with the
strokeStyle()
method, like so:
context.strokeStyle = "blue";
context.strokeRect(10,10,150,50);
Similarly, you can use the
fillRect(
x
,
y
,
width
,
height
)
method to make a rectangle,
but this time in a solid manner:
context.fillRect(150,30,75,75);
By default, the fill color will be black, but you can define a different fill color by using
the
fillColor()
method. As a demonstration this example sets a light red color:
context.fillStyle = "rgb(218,0,0)";
You can use standard CSS color functions, which may include opacity; for example, here
the opacity of the reddish fill is set to 40 percent:
context.fillStyle = "rgba(218,112,214,0.4)";
A full example using the first
canvas
element and associated JavaScript is presented here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>
HTML5 canvas example
</title>
<script type="text/javascript">
window.onload = function() {
var canvas = document.getElementById("canvas");