Dennis S
Dennis S

Reputation: 345

Generate SVG for HTML5 Canvas

I want to generate SVG as HTMLImageElement, so I can put it on <canvas> element. So here I am:

function makeButton(evt) {
    var svgns = "http://www.w3.org/2000/svg";

    var svg = document.createElementNS(svgns, "svg");
    svg.setAttribute('style', 'border: 1px solid black');
    svg.setAttribute('width', '59');
    svg.setAttribute('height', '59');
    svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

    var shape = document.createElementNS(svgns, "circle");
    shape.setAttributeNS(null, "cx", 25);
    shape.setAttributeNS(null, "cy", 25);
    shape.setAttributeNS(null, "r",  20);
    shape.setAttributeNS(null, "fill", "grey");

    svg.appendChild(shape);
    return svg;
}

And then:

var myButton = makeButton();
canvasContext.drawImage(myButton, offsetX, offsetY, width, height);

and it says, myButton is not an HTMLImageElement (is it XML) ?

Upvotes: 1

Views: 623

Answers (1)

jered
jered

Reputation: 11571

You can't draw an SVG directly onto the canvas because it's not an HTMLImageElement, it's an SVG element (duh).

The workaround is to create a new HTMLImageElement and use the SVG as its source.

var myButton = makeButton();
var svgData = new XMLSerializer().serializeToString(myButton);
var blob = new Blob([svgData], {type: "image/svg+xml;charset=utf-8"});
var url = window.URL.createObjectURL(blob);
var img = new Image();
img.src = url;
canvasContext.drawImage(img, offsetX, offsetY, width, height);

So what's going on here? Line by line:

  • Create new SVG element
  • Convert SVG to XML string (can't create a blob from an SVG element)
  • Create blob from XML string (a blob is basically raw data)
  • Use blob to create a URL we can use for our image src
  • Create new Image element
  • Set Image src to our blob URL
  • Draw Image on canvas

Edit: as was pointed out, it's a good idea to put the drawImage call inside of a callback so that you know the image element will be ready when it happens.

Upvotes: 2

Related Questions