【问题标题】:Firefox bug - globalCompositeOperation not working with drawImage for an SVG elementFirefox 错误 - globalCompositeOperation 不适用于 SVG 元素的 drawImage
【发布时间】:2016-03-02 06:59:38
【问题描述】:

我正在尝试在 Canvas 中创建“橡皮擦”效果,但使用 SVG 图像作为橡皮擦的自定义形状。

所以我可以将我的 SVG 图像绘制到画布上,并使用 globalCompositeOperation='destination-out' 创建遮罩效果。

它在 IE、Safari 和 Chrome 中运行良好。但它在 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>

【问题讨论】:

标签: html firefox canvas svg globalcompositeoperation


【解决方案1】:

这确实是一个错误,按照@RobertLongson 的建议,您应该在Mozilla's Buzilla 中提出一个错误。
但首先,你应该清理你的代码:ctx.beginPath() 没用。而ctx.closePath() 并没有按照你的想法去做。

如果您想解决此问题,可以先将 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>

【讨论】:

    猜你喜欢
    • 2013-08-08
    • 2015-04-14
    • 1970-01-01
    • 2018-06-30
    • 2019-01-28
    • 1970-01-01
    • 2022-06-20
    • 2021-02-07
    相关资源
    最近更新 更多