如何击出被击倒的物体?

时间:2014-05-15 17:15:44

标签: html5 canvas html5-canvas

在HTML5画布中,我试图用另一个对象敲出一个对象并描述该操作的最终产品。这有可能吗?我使用以下代码但没有成功:

var tcan = document.getElementById('test');
var tctx = tcan.getContext('2d');

tctx.beginPath();

tctx.fillStyle = '#F00';
tctx.fillRect(0,0,70,70);

tctx.globalCompositeOperation = "destination-out";

tctx.fillRect(20,20,70,70);
tctx.closePath();

tctx.strokeStyle = '#FF0'; // expecting the final product to have a yellow stroke
tctx.stroke();

1 个答案:

答案 0 :(得分:2)

演示:http://jsfiddle.net/m1erickson/x8Maf/

enter image description here

您可以使用source-atop合成在您现有的淘汰赛顶部绘制黄色笔划:

tctx.beginPath();

tctx.fillStyle = '#F00';
tctx.fillRect(0,0,70,70);

// knock-out compositing
tctx.globalCompositeOperation = "destination-out";

tctx.fillRect(20,20,70,70);
tctx.closePath();

// composite where new drawings appear only where overlapping existing
tctx.globalCompositeOperation = "source-atop";

tctx.strokeStyle = '#FF0'; // expecting the final product to have a yellow stroke
tctx.lineWidth=2;
tctx.strokeRect(20,20,70,70);

// restore the default compositing
tctx.globalCompositeOperation = "source-over";

一些提示:

  • 如果您使用fillRect或strokeRect(这些命令会自动为您启动路径),您不需要beginPath;

  • 所有画布笔划都在指定尺寸的一半内侧和一半外侧。所以fillRect(20,20,70,70)实际上会从19.50到20.50。

[除了回答:这里是如何击出淘汰赛的形状。 ]

var tcan = document.getElementById('test');
var tctx = tcan.getContext('2d');

tctx.lineWidth=2;
tctx.strokeStyle = '#FF0'; 

tctx.fillStyle = '#F00';
tctx.fillRect(50,50,70,70);
tctx.strokeRect(50,50,70,70);

// knock-out compositing
tctx.globalCompositeOperation = "destination-out";

tctx.fillRect(70,70,70,70);
tctx.closePath();

// composite where new drawings appear only where overlapping existing
tctx.globalCompositeOperation = "source-atop";

tctx.lineWidth=4;
tctx.strokeRect(70,70,70,70);

// restore the default compositing
tctx.globalCompositeOperation = "source-over";