← Glossary

What Is HTML Canvas Graphics?

HTML canvas is a browser element that provides a blank pixel surface which JavaScript draws onto through a rendering context such as CanvasRenderingContext2D, producing a bitmap rather than a set of retained shapes.

Updated:

HTML canvas is a browser element that gives a web page a rectangular pixel surface and lets JavaScript draw onto it. A script obtains a rendering context and issues commands to draw shapes, text or images onto its initially empty bitmap. The result is a bitmap. The browser keeps the pixels, not the shapes that produced them, which explains its strengths for pixel processing and the extra work needed for interaction.

HTML canvas is distinct from Canva, the online design application.

Drawing into a Canvas

After adding the element, a script calls getContext("2d") and draws through the returned CanvasRenderingContext2D. For example, a monitoring panel can paint a background, add a line graph, then draw labels. Each command combines new pixels with the existing bitmap according to the context’s compositing settings.

This is immediate-mode canvas drawing. The context has a current state, including fill and stroke styles, line width, font, shadow settings and a transformation matrix, and each command applies that state at the moment it runs. There is no object to select afterwards. To move a rectangle, the script clears its old pixels and paints it again in the new place; an animation often clears and redraws each frame, although applications can update only changed regions. The save() and restore() methods push and pop the state onto a stack so a temporary rotation or colour change can be undone without manually resetting each property.

Content placed between the opening and closing tags is fallback. Supporting browsers normally display the bitmap visually, but fallback content can provide an accessible alternative. Interactive graphics need equivalent controls and meaningful descriptions; merely putting an empty canvas on the page does not communicate its contents.

Pixels, Coordinates and Rendering Contexts

A canvas has two sizes that are easy to conflate. The width and height attributes set the size of the bitmap in pixels and default to 300 by 150 when omitted. CSS can then stretch or shrink the element on the page, but the bitmap is simply scaled to fit, so a 300 by 150 bitmap displayed at 600 by 150 shows every shape twice as wide. For crisp output on high-density screens, the bitmap is commonly sized to the CSS dimensions multiplied by the device pixel ratio. The drawing coordinate system must be scaled accordingly, and resizing the bitmap resets its contents and context state.

Coordinates start at the top-left corner, with x increasing to the right and y increasing downward. The transformation methods, translate(), rotate(), scale() and setTransform(), change how subsequent coordinates map onto the bitmap, which is how a script draws around a different origin or flips an axis without recalculating every point.

The getContext() method accepts several context types, and this is where the HTML canvas element becomes more than a 2D drawing surface. 2d returns the familiar context. webgl and webgl2 return WebGL contexts that render hardware-accelerated 2D and 3D graphics through shader programs. webgpu returns the canvas context for the newer GPU API. bitmaprenderer displays an image bitmap with no drawing API at all. A canvas commits to the first context type successfully created; asking the same element for a different type afterwards returns null, while repeating the same type returns the same context object.

Context options affect rendering tradeoffs. An opaque canvas can avoid some transparency work. The willReadFrequently hint allows the browser to favour storage suited to repeated pixel reads, potentially sacrificing drawing speed. A canvas transferred to an OffscreenCanvas can be controlled from a worker instead of obtaining a new context on the original element.

What the 2D Context Provides

The 2D methods cover several tasks.

  • Rectangles are drawn or erased directly with fillRect(), strokeRect() and clearRect(), with clearing normally restoring transparent pixels on a canvas that supports alpha.
  • Paths are assembled with beginPath(), moveTo(), lineTo(), arc() and curve methods, then rendered with fill() or stroke(). Rendering does not discard the current path; beginPath() starts a new one. A reusable Path2D can also preserve a path description separately from the bitmap.
  • Text is placed with fillText() and strokeText() using the current font; measureText() reports its width.
  • Images, video frames and other canvases are copied in with drawImage(), optionally cropped and scaled.
  • Pixel data is read with getImageData(), which returns pixel values for a region, edited in JavaScript, and written back with putImageData(). This is the route for filters, colour analysis and anything that needs the actual numbers.

The bitmap can also be exported. toDataURL() encodes the canvas as a PNG by default, or as JPEG or WebP where supported, and toBlob() does the same more efficiently for large images. If an image from another origin is drawn without a successful CORS-enabled load, the canvas is considered tainted and both export and pixel read-back throw a security error, preventing the page from extracting protected cross-origin pixels. The image can still be visible even when reading its pixels is forbidden.

Canvas vs SVG and DOM Layout

SVG provides a different graphics model.

PropertyHTML canvasSVG
ModelBitmap; pixels onlyRetained vector objects in markup
ScalingBlurs when enlarged beyond bitmap sizeVector shapes remain sharp when scaled
InteractionScript must map clicks to shapes itselfEach element receives DOM events
StylingSet in script per commandCSS applies to elements
Accessibility and searchNeeds accessible descriptions and equivalent controlsCan expose text and structure; authoring still matters
Performance patternBitmap work and redraw costs depend on workloadCost grows with element count

In the canvas vs SVG decision, SVG is often convenient for icons and diagrams whose shapes need styling or individual events. Canvas can suit dense plots, frequently changing scenes and pixel processing. There is no fixed point count at which one becomes faster; redraw frequency, effects and implementation matter. Canvas contents are not DOM nodes. CSS positions the canvas rectangle; the drawing code positions its contents. A financial chart, for instance, can pair the canvas visualisation with an HTML data table and normal buttons for adjusting the view.

Uses and Limitations

Typical canvas work includes game rendering, animation, data visualisation with very large datasets, image editors and real-time processing of camera or video frames. OffscreenCanvas extends this to web workers so drawing coordination can run away from the main thread, although shared CPU or GPU pressure can still affect responsiveness.

The limitations follow from the bitmap model. Painted text does not automatically gain native text selection or screen-reader semantics. Browser zoom can enlarge the canvas, but a fixed bitmap may blur unless the application redraws at an appropriate resolution. Anything interactive requires the script to keep its own record of what is where. Rendering output can differ slightly between machines because of fonts, anti-aliasing and GPU differences, and because that variation can be measured, canvas read-back is also used in fingerprinting, which is a separate subject from drawing itself. Choosing canvas means accepting responsibility for redraws, interaction and accessible alternatives, alongside the freedom to work directly with pixels.

Frequently asked questions

Is canvas the same as Canva?

No. HTML canvas is a browser element and drawing API used by web developers. Canva is a commercial online design application. Searches for 'canvas graphics' return both, but they are unrelated; this article covers only the browser element.

Does canvas store a vector drawing?

The visible output is a bitmap, not a tree of editable vector objects. The current path or a Path2D object can preserve drawing instructions, but moving a rendered shape still requires redrawing pixels. Applications can maintain their own scene model or use SVG for retained elements.

Can canvas use WebGL instead of a 2D context?

Yes. Calling getContext with 'webgl' or 'webgl2' returns a WebGL context on the same element, and 'webgpu' returns a WebGPU canvas context. A canvas is bound to the first context type it hands out, so one element cannot be both 2D and WebGL.

Why does a canvas look blurry or stretched?

Often the bitmap resolution does not match its display size or aspect ratio. Size the bitmap for the CSS dimensions and device pixel ratio, then adjust the drawing transform. Remember that changing bitmap dimensions clears the image and resets context state, so the content must be redrawn.

Can a page read the pixels it drew?

Yes, through getImageData, toDataURL or toBlob, as long as the canvas is not tainted by cross-origin images loaded without CORS permission. Because rendering varies slightly between devices, this read-back is also what canvas fingerprinting measures, which is a separate topic.