The canvas element is used to draw graphics on a web page.
Your browser does not support the canvas element.
What is Canvas?
The HTML5 canvas element uses JavaScript to draw graphics on a web page.A canvas is a rectangular area, and you control every pixel of it.
The canvas element has several methods for drawing paths, boxes, circles, characters, and adding images.
Create a Canvas Element
Add a canvas element to the HTML5 page.Specify the id, width, and height of the element:
<canvas id="myCanvas" width="200" height="100"></canvas>
Draw With JavaScript
The canvas element has no drawing abilities of its own. All drawing must be done inside a JavaScript:
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
</script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
</script>
Try it yourself »
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
The next two lines draws a red rectangle:
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,75);
ctx.fillRect(0,0,150,75);
Understanding Coordinates
The fillRect method above had the parameters (0,0,150,75).This means: Draw a 150x75 rectangle on the canvas, starting at the top left corner (0,0).
The canvas' X and Y coordinates are used to position drawings on the canvas.
Mouse over the rectangle below to see the coordinates:
X
Y
More Canvas Examples
Below are more examples of drawing on the canvas element:Example - Line
Draw a line by specifying where to start, and where to stop:
Your browser does not support the canvas element.
Try it yourself »
Example - Circle
Draw a circle by specifying the size, color, and position:
Your browser does not support the canvas element.
Try it yourself »
Example - Gradient
Draw a gradient background with the colors you specify:
Your browser does not support the canvas element.
Try it yourself »
HTML5 <canvas> Tag
Tag | Description |
---|---|
<canvas> | Defines graphics |
No comments:
Post a Comment