Canvas Draw Image Issue On Firefox, Works Well In Chrome
I will assume this is some sort of compatibility issue. Everything works perfectly in chrome, but in firefox the
Solution 1:
Your problem is that the image your are trying to draw are svg images, and that these svg documents have relative width
and height
attributes.
The browser can't set a height nor a width to the image it has to draw, and hence it can't render it to the canvas. (It is able to do an estimation in the document, since it can be relative to something, but not in the canvas).
So the solution is to set absolute width
and height
attributes in your svg files,
Or, more complicated, to first draw it into an <iframe>
or an <object>
, then draw a serialized version where you'll have set these attributes.
functioninitialize() {
var canvas = document.getElementById("char1Canvas");
var canvasContext = canvas.getContext("2d");
var image = document.getElementById("char1Img");
resizeSVG(image, function(e){
canvasContext.clearRect(0, 0, 1280, 1280);
canvasContext.drawImage(this, 0, 0);
});
};
var resizeSVG = function(svgImg, callback){
// create an iframevar iframe = document.createElement('iframe');
// so we don't see it
iframe.height = 0;
iframe.width = 0;
iframe.onload = function(){
var doc = iframe.contentDocument;
var svg = doc.querySelector('svg');
// get the computed width and height of your img element// should probably be tweakedvar bbox = svgImg.getBoundingClientRect();
// if it's a relative widthif (svg.width.baseVal.unitType !== 1) {
svg.setAttribute('width', bbox.width);
}
// or a relative heightif (svg.height.baseVal.unitType !== 1) {
svg.setAttribute('height', bbox.height);
}
// serialize our updated svgvar svgData = (newXMLSerializer()).serializeToString(svg);
var svgURL = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgData);
// create a new Image Object that ill be draw on the canvasvar img = newImage();
img.onload = callback;
img.src = svgURL;
// remove the iframedocument.body.removeChild(iframe);
};
iframe.src = svgImg.src;
document.body.appendChild(iframe);
}
Post a Comment for "Canvas Draw Image Issue On Firefox, Works Well In Chrome"