在HTML5画布中遮罩形状? [英] Masking shapes in HTML5 canvas?

查看:186
本文介绍了在HTML5画布中遮罩形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

道歉,如果有人在其他地方被问过,但很难说出来,因为我找不到任何东西。



有什么方法可以在画布中实现遮罩?



例如,仅使用形状(无图像)我用窗户绘制房屋。我也有一个代表一个人的形状。我希望那个人出现在窗户上 - 但显然只有窗户允许的那么多才能看到这个人。其余的将被掩盖。



我想清空窗户占用的部分房间,使得图层中有一个真正的洞,这使得问题容易解决。



但我意识到你不能删除画布中的形状或部分形状,只能画出新东西而不是旧东西。所以在一个多层次的环境中(我在Kinetic.JS中制作游戏),我该怎么办?



对不起,新的整体图形的东西。

解决方案

你应该很快了解剪辑和合成,但这些都不是你实际需要的这里。



相反,您需要学习如何使用非零绕组数规则来制作路径,这是HTML5画布使用的。



如果顺时针绘制部分路径而逆时针绘制另一部分路径,则可以从路径中切出形状。



以下是一个窗口示例:



http:// jsfiddle.net/simonsarris/U5bXf/






编辑:这里有一点为您呈现非零卷数规则的可视化:



在一个方向上绘制子路径,并且路径交叉的地方将填充(或不填充)空格。

如果你将手指放在图的任何部分,并想象一条线从你的手指伸出到空的空间中,那条线穿过一条倍。如果从零开始,为每个顺时针路径加1,并为每个逆时针路径减1,填充区域就是所有非零数字的区域。这些区域的数字在上图中给出。


Apologies if this has been asked elsewhere but it's pretty hard to phrase as it is so I couldn't find anything.

Is there any way to implement masks in canvas?

For example, using shapes only (no images) I draw a house with a window. I also have a shape representing a person. I want that person to appear at the window - but obviously only so much as the window allows should be visible of the person. The rest would be masked.

I thought about emptying the part of the house occupied by the window, such that there was a genuine hole in the layer, which makes the problem easy to solve.

But I'm conscious you can't delete shapes or parts of shapes in canvas, only draw new stuff over old stuff. So in a multi-layered environment (I'm making a game in Kinetic.JS), what exactly can I do?

Sorry if any of this is poorly explained - new to the whole graphic thing.

解决方案

You should learn about clipping and compositing soon, but neither of these are what you actually need here.

Instead you need to learn how to make paths using the non-zero winding number rule, which is what HTML5 canvas uses.

If you draw part of your path clockwise and another part counter-clockwise, you can "cut out" shapes from your path.

Here's an example with a window:

http://jsfiddle.net/simonsarris/U5bXf/


edit: Here's a bit of a visualization for you of how the nonzero winding number rule works:

Subpaths are drawn in a direction, and where the paths cross you'll get filled (or not) spaces.

If you put your finger on any part of the figure, and imagine a line going from your finger out into the empty space, that line crosses the path a number of times. If you start at zero and add 1 for every clockwise path, and subtract 1 for every counterclockwise path, the filled areas are all of the areas that have a non-zero number. The numbers for the areas are given in the above diagram.

这篇关于在HTML5画布中遮罩形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆