Content
- Canvas
- Canvas reference
The new canvas element (<canvas>) of HTML5 provides an Application Programming Interface (API) for two-dimensional drawing—lines, fills, images, text, and so on.
The canvas is only a container for graphics, a script (e.g., JavaScript) must be used to actually draw the graphics.
Every pixel in the canvas can be controlled.
Here is a simple example of use of the canvas element:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas example</title>
<script>
function draw()
{
var ctx = document.querySelector("canvas").getContext("2d");
// First square
ctx.fillRect(10, 10, 50, 50);
// Second square
ctx.fillRect(100, 100, 50, 50);
}
window.onload = draw;
</script>
<body>
<canvas></canvas>
</body>
</html>
Any text inside the <canvas> element will be displayed in browsers that does not support <canvas>.
Therefore, it can be used to offer a fallback option:
<canvas> <p> Your browser doesn't support <canvas> element. Please, downdload and use one of the following browsers: </p> <ul> <li>Google Chrome</li> <li>Mozilla Firefox</li> <li>Opera</li> </ul> </canvas>
Canvas properties
fillStyle = color|style
The fill-color of the drawing.strokeStyle = color|style
The stroke-color of the drawing.lineCap = butt|round|square
The style of the ending of the line.lineJoin = bevel|round|miter
The style of the corners of the line.lineWidth = number
The width of the drawing stroke.miterLimit = number
The limit size of the corners in a line.shadowColor = color
The color of the shadow.shadowOffsetX = number
The horizontal distance of the shadow.shadowOffsetY = number
The vertical distance of the shadow.shadowBlur = number
The size of the burring effect.
Canvas methods
Some of the most important canvas methods:
fillRect(x, y, width, height)
Draws a filled rectangle using the color/style of thefillStyleattribute. Thexandycoordinates start in the top left.strokeRect(x, y, w, h)
Draws the lines of a rectangle using the color/style of thestrokeStyleattribute.clearRect(x, y, w, h)
Clears a rectangle area.rect(x, y, w, h)
Creates a rectangle.moveTo(x, y)
Moves the path to the specified point, without creating a line.lineTo(x, y)
Creates a line from the last point in the path to the given point.arc(x, y, r, sAngle, eAngle, aClockwise)
Creates a circle, or parts of a circle.arcTo(x1, y1, x2, y2, radius)
Creates an arc between two points.
More information: