What is canvas?
The <canvas>
tag in HTML5 is used to draw images (via scripts, usually JavaScript). However, the <canvas>
element itself has no drawing ability. It is only a container of graphics. We must use scripts to complete the actual drawing task.
Create canvas element
Add the canvas element to the HTML 5 page and specify the ID, width, and height of the element:
<canvas id="myCanvas" width="200" height="200">
<p>Your browser does not support canvas! </p>
</canvas>
Draw with JavaScript
Canvas element itself has no drawing ability. All the drawing work must be done in javascript:
<script type="text/javascript">
var canvas=document.getElementById("myCanvas");
var cxt=canvas.getContext("2d");
cxt.fillStyle="red";
cxt.fillRect(0,0,150,75);
</script>
Where JavaScript uses id
to find the canvas
element:
var canvas=document.getElementById("myCanvas");
Then, create the context
object:
var cxt=canvas.getContext("2d");
getContext("2d")
objects are built-in HTML5 objects, which have many ways to draw paths, rectangles, circles, characters and add images.
Next, draw a red rectangle in two lines of code:
cxt.fillStyle="red";
cxt.fillRect(0,0,150,75);
It is dyed red by fillStyle
method, and the shape, position and size are specified by fillRect method.
Understanding of coordinates
The fillRect
method in the code has parameters (0,0150,75)
. This means drawing a 150x75
rectangle on the canvas, starting at the top left corner (0,0)
.
As shown in the following figure, the X and Y coordinates of the canvas are used to locate the painting on the canvas.