Canvas Draw Image issue on firefox, works well in chrome

前端 未结 1 686
离开以前
离开以前 2020-11-30 15:00

I will assume this is some sort of compatibility issue. Everything works perfectly in chrome, but in firefox the simply doesn\'t draw anything.

相关标签:
1条回答
  • 2020-11-30 16:07

    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.

    function initialize() {
        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 iframe
        var 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 tweaked
            var bbox = svgImg.getBoundingClientRect();
            // if it's a relative width
            if (svg.width.baseVal.unitType !== 1) {
                svg.setAttribute('width', bbox.width);
            }
            // or a relative height
            if (svg.height.baseVal.unitType !== 1) {
                svg.setAttribute('height', bbox.height);
            }
            // serialize our updated svg
            var svgData = (new XMLSerializer()).serializeToString(svg);
            var svgURL = 'data:image/svg+xml; charset=utf8, ' + encodeURIComponent(svgData);
            // create a new Image Object that ill be draw on the canvas
            var img = new Image();
            img.onload = callback;
            img.src = svgURL;
            // remove the iframe
            document.body.removeChild(iframe);
        };
        iframe.src = svgImg.src;
        document.body.appendChild(iframe);
    }
    
    0 讨论(0)
提交回复
热议问题