html5 canvas - 合并两个剪辑区域 - James Bond Gunbarrel

Posted

技术标签:

【中文标题】html5 canvas - 合并两个剪辑区域 - James Bond Gunbarrel【英文标题】:html5 canvas - merge two clipping regions - James Bond Gunbarrel 【发布时间】:2012-08-14 13:17:11 【问题描述】:

我刚刚开始使用canvas来获得这种效果:

“詹姆斯邦德枪管视图开始” http://www.youtube.com/watch?v=sfXazFp68cE

我几乎到了那里:

http://jsbin.com/uyaker/8/edit

现在你可以看到我用两个圆圈剪辑我的画布(至少我尝试过)......但问题是重叠的区域不再被剪辑......

ctx.clearRect(0, 0, canvas.width, canvas.height);    
ctx.save();
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(canvas.width, 0);
ctx.lineTo(canvas.width, canvas.height);
ctx.lineTo(0, canvas.height);
ctx.closePath();
ctx.moveTo(cx + r, cy);
ctx.arc(cx, cy, r, 0, Math.PI*2, true);
// check if to draw a fixed circle, every 200 pixels for 100 pixels
if(goingright && cx % 200 < 100) 
    ctx.moveTo(cx - cx % 200 + r, cy);
    ctx.arc(cx - cx % 200, cy, r, 0, Math.PI*2, true);

ctx.closePath();
ctx.clip();

ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();

也许这种效果在不使用剪辑的情况下是可能的,但给画布一个 css 背景图像并绘制除圆圈之外的所有内容......但我真的不知道该怎么做:/。

【问题讨论】:

【参考方案1】:

Maybe this effect is possible without using clipping ... but I don't really know how to do that

是的,有可能,您需要创建一个可以完成所有工作的路径:

context.beginPath();
context.moveTo(x, y);
// Draw your big shape, in your case is a rectangle (4 point)
context.lineTo(xn, yn);
context.closePath();
// Now the context knows that every path that will be added without .beginPath(), will clip the current path
context.arc(cx, cy, r, 0, Math.PI * 2, true);
context.closePath();
context.fill(); // Fill with color all the area except the arc

示例:http://jsfiddle.net/drhWb/

保存、恢复和剪辑上下文是非常昂贵的操作,因此您应该使用这种方法是您需要采用的正确方法。

【讨论】:

非常感谢...但是当我添加: context.arc(context.canvas.width / 2 - 50, context.canvas.height / 2, 50, 0, Math.PI* 2、真);在第一个 arc 语句之后,您会看到这两个圆圈的重叠区域没有被剪裁:( 我建议您使用 canvas API CheatSheet: nihilogic.dk/labs/canvas_sheet/html5_Canvas_Cheat_Sheet.png ,并查看 globalCompositeOperation,进行实验,看看有什么可以帮助您,我正在开发一个库,可以简化使用 html5 的工作画布,它才刚刚开始,但我会尝试让裁剪操作非常易于理解和使用。 我终于使用 raphael.js raphaeljs.com 实现了这一点……现在它可以跨浏览器兼容了……虽然没那么花哨,但至少应该在所有浏览器中都可以使用:jsfiddle.net/cr4Hv/1

以上是关于html5 canvas - 合并两个剪辑区域 - James Bond Gunbarrel的主要内容,如果未能解决你的问题,请参考以下文章

如何创建中间有孔的画布 html5 剪辑区域?

HTML5 Canvas 剪辑与前一个剪辑重叠

如何在 html 5 画布中删除区域的剪辑

html5画布:按颜色剪裁

Canvas系列 | 剪辑区域函数clip

Html5 Canvas + fabric.js 的独立堆肥