简体   繁体   English

Firefox错误-globalCompositeOperation无法与SVG元素的drawImage一起使用

[英]Firefox bug - globalCompositeOperation not working with drawImage for an SVG element

I'm trying to create an 'eraser' effect in Canvas, but using an SVG image as a custom shape for the eraser. 我正在尝试在Canvas中创建“橡皮擦”效果,但是将SVG图像用作橡皮擦的自定义形状。

So I can draw my SVG image to canvas, and use globalCompositeOperation='destination-out' to create a masking effect. 因此,我可以将我的SVG图像绘制到画布上,并使用globalCompositeOperation ='destination-out'创建遮罩效果。

It works great in IE, Safari, and Chrome. 它在IE,Safari和Chrome中都很好用。 But it utterly fails in Firefox. 但它在Firefox中完全失败。

  function init() { var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); var img = document.createElement('IMG'); img.onload = function () { ctx.beginPath(); ctx.drawImage(img, 0, 0); ctx.closePath(); ctx.globalCompositeOperation = 'destination-out'; } img.src = "http://www.evanburke.com/FROST.png"; var svg = new Image; svg.src = "http://www.evanburke.com/luf.svg"; function drawPoint(pointX,pointY){ ctx.drawImage(svg,pointX,pointY); } canvas.addEventListener('mousemove',function(e){ drawPoint(e.clientX,e.clientY); },false); } 
  <body onload="javascript:init();"> <div> <canvas id="c" width="400" height="400"></canvas> </div> </body> 

That's indeed a bug, and as advised by @RobertLongson, you should raise a bug in Mozilla's Buzilla . 这确实是一个错误,按照@RobertLongson的建议,您应该在Mozilla的Buzilla中引发一个错误。
But first, you should clean up your code : ctx.beginPath() is useless. 但是首先,您应该清理代码: ctx.beginPath()没有用。 and ctx.closePath() doesn't do what yo think it does. ctx.closePath()并没有您所想的那样。

If you want a workaround for this issue, you could first draw the svg image onto a canvas, then use this canvas as the eraser : 如果您需要解决此问题的方法,可以先将svg图像绘制到画布上,然后将该画布用作橡皮擦:

 (function init() { var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); var svgCan; var img = document.createElement('IMG'); img.onload = function() { ctx.drawImage(this, 0, 0); ctx.globalCompositeOperation = 'destination-out'; } img.src = "http://www.evanburke.com/FROST.png"; var svg = new Image(); svg.src = "http://www.evanburke.com/luf.svg"; svg.onload = function() { // create a canvas svgCan = canvas.cloneNode(); svgCan.width = this.width; svgCan.height = this.height; // draw the svg on this new canvas svgCan.getContext('2d').drawImage(svg, 0, 0); } function drawPoint(pointX, pointY) { // this is now a pixel image that will work with gCO ctx.drawImage(svgCan, pointX, pointY); } canvas.addEventListener('mousemove', function(e) { drawPoint(e.clientX, e.clientY); }, false); })() 
 <div> <canvas id="c" width="400" height="400"></canvas> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM