I have added background image to canvas using css.
But when converting it into png using canvas.toDataURL() , its not showing background image.
It seems like its not parsing css background image.
var svgString = new XMLSerializer().serializeToString(document.querySelector('svg'));
var canvas = document.getElementById("canvas");
d3.select('canvas')
.attr('style', 'background-image:url("chart.png");background-position:50%;background-repeat:no-repeat');
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
//var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var svg = new Blob([svgString], {type: "image/svg+xml"});
var url = DOMURL.createObjectURL(svg);
var png = '';
img.onload = function() {
ctx.drawImage(img, 0, 0);
png = canvas.toDataURL("image/png");
document.querySelector('#chart').innerHTML = '<img src="'+png+'"/>';
DOMURL.revokeObjectURL(png);
img.src = "";
};
img.crossOrigin = "anonymous";
img.src = url;
As said in comments,
background-image
is not part of the canvas context and thus, can't be exported by any canvas' export methods.If you want to get this image drawn on the canvas, simply draw it before you draw the other image.* The main difficulty being to reproduce the different option CSS background has. But in your case, it's quite simple.
*As said by markE, if you can't draw the background before, you can also set the
globalCompositeOperation
of your context todestination-over
in order to draw behind the actual content.Now, this wasn't clearly part of your question, but if you tried to set the
background-image
to your svg node, you should have been able to draw it on your canvas image, as part of the svg.But since HTMLImage (
<img>
) element can't load any external resources form its loaded media, you would have to first convert the image to a dataURI version, and append the styles either as the svg'sstyle
attribute, either in a<style>
element appended inside the svg element.Here is a ugly example that will convert an svg element with a CSS defined background-image, and draw it on the canvas.
Don't use it, this just here for the demo but is likely to break. Also, this has only been quickly tested against FF, Chrome and Safari.