HTML <canvas> Element

Publish in HTML Tutorial el 23/05/2025 17:40

The HTML <canvas> element provides a resolution-dependent bitmap canvas that can be used for rendering graphs, game graphics, art, or other visual images on the fly using JavaScript. It's essentially a drawable region defined in HTML code with height and width attributes.


Key characteristics of <canvas>:

  • Requires JavaScript to actually draw graphics
  • Has several methods for drawing paths, boxes, circles, text, and adding images
  • Is supported in all modern browsers
  • Provides a powerful API for pixel manipulation

Basic Canvas Syntax

Here's how to define a basic canvas element in HTML:


Canvas Rendering Context

To actually draw on the canvas, you need to get its rendering context:


Canvas Examples


Example 1: Drawing a Rectangle

This example shows how to draw a simple filled rectangle on a canvas.

Play Code


Example 2: Drawing a Circle

This example demonstrates how to draw a circle using the arc method.

Play Code


Example 3: Drawing Text

Canvas can also render text with various styling options.

Play Code


Example 4: Simple Animation (JavaScript)

This example shows a basic animation of a bouncing ball using JavaScript.

Play Code


Example 5: Drawing an Image (JavaScript)

This example demonstrates how to load and draw an image onto the canvas.

Play Code


Tips and Tricks

  • Performance: For complex animations, consider using requestAnimationFrame instead of setInterval or setTimeout.
  • Retina Displays: To make canvas look sharp on high-DPI displays, double the canvas size and scale it down using CSS.
  • Clearing: Use clearRect(0, 0, width, height) to clear the canvas between frames.
  • Save/Restore: Use ctx.save() and ctx.restore() to manage the drawing state.
  • Optimization: For static elements, draw them once to an offscreen canvas and then copy to the main canvas.


Browser Support

The <canvas> element is supported in all modern browsers, including:

  • Chrome 4+
  • Firefox 2+
  • Safari 3.1+
  • Opera 9+
  • Edge 12+
  • Internet Explorer 9+

También te puede interesar

HTML <style> Element
HTML <style> Element

The <style> HTML element contains style information for a document, or part of a document. ...

HTML <strong> Element
HTML <strong> Element

The <strong> element is used to indicate that its content has strong importance, seriousnes...

HTML <span> Element
HTML <span> Element

The <span> element is an inline container used to mark up a part of a text or document. Unl...

HTML <source> Element
HTML <source> Element

The <source> element is used to specify multiple media resources for media elements like &l...

HTML <small> Element
HTML <small> Element

The <small> element is used to represent side-comments and small print, typically for discl...

HTML <section> Element
HTML <section> Element

HTML <section> Element: The Complete Guide The <section> element is a semantic HTML ...