drawable

The drawable attribute marks an SVG element as a paint root, meaning that it can be rendered independently on a parent <canvas> element with its content attribute set to drawable, using the HTML-in-Canvas API.

The drawable attribute is a boolean attribute; its presence marks a <canvas> descendant as a paint root.

You can use drawable with any renderable attribute, including shape, structural, and text content elements.

Examples

Basic usage

This example shows how to render SVG onto a 2D canvas.

HTML

We include a <canvas> element with its content attribute set to drawable. Nested inside the canvas we include an <svg> element containing a <circle>. The <svg> element has the drawable attribute set.

html
<canvas width="480" height="320" content="drawable">
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" drawable>
    <circle cx="20" cy="20" r="15" tabindex="0" />
  </svg>
</canvas>

CSS

We set some rudimentary styles on the <circle> element. As you'll see in the result, the HTML is rendered on the canvas exactly as styled by the CSS.

css
circle {
  stroke: black;
  stroke-width: 2px;
  fill: red;
  outline: none;
}

circle:hover,
circle:focus {
  fill: blue;
}

JavaScript

In our script, we first grab references to our <canvas> and <svg> elements.

js
const canvas = document.querySelector("canvas");
const svgElem = document.querySelector("svg");

Next, we define a main() function. Inside, we get a 2D canvas context using the getContext() method. Next, we check if the drawElementImage() method exists on the context; if not, we add a no-html-in-canvas class to the <body> element that is used to display a "no support" banner.

Next, we use the drawElementImage() method to draw the <svg> element onto the canvas. We do this inside a paint event so that the <svg> element is redrawn on the canvas each time it is repainted. This includes the initial paint, and the repaint each time the circle is focused or hovered.

js
function main() {
  const ctx = canvas.getContext("2d");

  if (!ctx.drawElementImage) {
    document.body.className = "no-html-in-canvas";
    return;
  }

  canvas.addEventListener("paint", () => {
    ctx.drawElementImage(svgElem, 10, 10);
  });
}

Finally, we run the main() function to start the example:

js
main();

Result

Specifications

This feature does not appear to be defined in any specification.

Browser compatibility

See also