详解FireFox下Canvas使用图像合成绘制SVG的Bug

2020-04-21 22:43:49易采站长站整理

比如上面代码可以改进如下:


function init() {
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0, img.width * 2, img.height * 2);
ctx.globalCompositeOperation = 'destination-out';
}
img.src = 'diffuse.png';
var svg = new Image;
svg.src = "./d.svg";

var tempCanvas = svg;
if(isFirefox){
svg.onload = function(){
tempCanvas = document.createElement('canvas');
tempCanvas.width = svg.width;
tempCanvas.height = svg.height;
var tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(svg,0,0,svg.width,svg.height);
}
}

function drawPoint(pointX, pointY) {

ctx.drawImage(tempCanvas, pointX - svg.width / 4, pointY - svg.height / 4, svg.width / 2, svg.height / 2);
}
canvas.addEventListener('click', function (e) {
drawPoint(e.clientX, e.clientY);
}, false);
}