The HTML <canvas> element is used to draw graphics on a web page. Graphics are created using JavaScript.
HTML Canvas allows you to draw:
<canvas id="myCanvas" width="200" height="100"> </canvas>
A canvas is a rectangular drawing area.
<canvas id="canvas1" width="300" height="150" style="border:1px solid black;"> </canvas>
Always specify:
JavaScript accesses the drawing area using getContext().
var c=
document.getElementById(
"myCanvas"
);
var ctx=
c.getContext("2d");
The 2D context is used for drawing.
ctx.moveTo( 0, 0 ); ctx.lineTo( 200, 100 ); ctx.stroke();
The stroke() method draws the line.
ctx.beginPath(); ctx.arc( 95, 50, 40, 0, 2*Math.PI ); ctx.stroke();
The arc() method creates circles and arcs.
The fillRect() method draws a filled rectangle.
ctx.fillRect( 20, 20, 150, 100 );
Parameters:
Canvas can display text.
ctx.font= "30px Arial"; ctx.fillText( "Hello", 20, 50 );
fillText() draws filled text.
Images can be displayed inside a canvas.
var img= document.getElementById( "img1" ); ctx.drawImage( img, 10, 10 );
drawImage() places the image on the canvas.
| Feature | Purpose |
|---|---|
| Line | Draw lines |
| Rectangle | Draw boxes |
| Circle | Draw circles |
| Text | Display text |
| Image | Display images |
| Fill | Fill color |
| Stroke | Draw outlines |
| Animation | Create motion |
Which method is used to get the 2D drawing context?