The HTML Canvas Reference provides a comprehensive list of methods and properties for manipulating the <canvas>
element. This powerful tool allows developers to create dynamic, interactive graphics directly within web pages.
To begin working with canvas, you must first obtain its rendering context. The most common context is '2d', used for two-dimensional graphics.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
The canvas API offers various methods for drawing shapes, lines, and paths. Here are some fundamental drawing methods:
fillRect(x, y, width, height)
: Draws a filled rectanglestrokeRect(x, y, width, height)
: Draws a rectangular outlinebeginPath()
: Starts a new pathmoveTo(x, y)
: Moves the pen to specified coordinateslineTo(x, y)
: Draws a line to specified coordinatesarc(x, y, radius, startAngle, endAngle, anticlockwise)
: Draws an arc or circleCustomize your canvas drawings with these styling properties:
fillStyle
: Sets the color or style for filled shapesstrokeStyle
: Sets the color or style for shape outlineslineWidth
: Sets the width of linesfont
: Specifies the font for text drawingCanvas allows you to render text with these methods:
fillText(text, x, y [, maxWidth])
: Draws filled textstrokeText(text, x, y [, maxWidth])
: Draws text outlinesLet's create a simple drawing that demonstrates some of these methods and properties:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a filled rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 80);
// Draw a line
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(110, 100);
ctx.strokeStyle = 'red';
ctx.lineWidth = 5;
ctx.stroke();
// Draw some text
ctx.font = '20px Arial';
ctx.fillStyle = 'green';
ctx.fillText('Hello, Canvas!', 10, 150);
save()
and restore()
methods to manage drawing statesThe canvas element is widely supported in modern browsers. However, always provide fallback content for older browsers or those with JavaScript disabled.
To further enhance your canvas skills, explore these related topics:
By mastering the HTML Canvas Reference, you'll be equipped to create rich, interactive graphics for web applications, data visualizations, and more. Remember to consult the official documentation for the most up-to-date and comprehensive information on canvas methods and properties.