0

我正在尝试在 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>

4

1 回答 1

0

这确实是一个错误,正如@RobertLongson 所建议的,您应该在Mozilla 的 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>

于 2015-11-28T09:35:40.793 回答