Reputation: 345
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
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:
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