当形状部分透明时,如何在Canvas中从另一个形状(XOR)切出一个形状? [英] How do a cut out one shape from another (XOR) in Canvas when shape is partially transparent?

查看:73
本文介绍了当形状部分透明时,如何在Canvas中从另一个形状(XOR)切出一个形状?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常是使用Canvas从一种形状中切出一个形状,我使用了globalCompositeOperation选项"xor":

Normally to cut one shape out from another using Canvas, I've used the globalCompositeOperation option "xor":

var c2 = document.getElementById('canvas').getContext('2d');
c2.globalCompositeOperation = "xor";
c2.fillRect(0, 0, 200, 200);
c2.fillRect(170, 0, 30, 30); // shape 2 is cut out from shape 1

但是,当fillStyle的Alpha值<1,否则上下文的globalAlpha是<1,切口"形状不再完全不可见.

However, when either the fillStyle has a alpha value < 1, or the globalAlpha of the context is < 1, the "cut-out" shape is no longer completely invisible.

具体地说,如果Alpha值大于0.5且小于1,您会看到较浅的形状.如果Alpha为0.5,则根本没有可见的切口.并且如果alpha <0.5,我们得到相反的结果:应该被切除的形状实际上比第一个形状更暗.

Specifically, if the alpha is >0.5 and <1, you see a lighter version of the shape. If the alpha is 0.5, there is no cut-out visible at all. And if alpha is <0.5, we get the inverse: the shape that's supposed to be cut out is in fact darker than the first shape.

可以在 http://jsfiddle.net/N7aXY/2/上看到.

您可以尝试更改alpha值以查看不同的效果.

You can try changing the alpha value to see the different effects.

当背景形状的alpha值小于<时,是否有任何方法可以完全切出形状?1?

Is there any way to completely cut out a shape when the background shape has an alpha < 1?

推荐答案

好的,这有点骇人听闻",但是无论如何我们还是要这样做:

Ok, this is a bit "hackish", but here we go anyway:

  1. 将合成设置为XOR.
  2. 通常从shape1绘制到剪切" shape2.
  3. 保存画布.
  4. 将合成设置为普通(来源).
  5. 将globalAlpha设置为所需的水平.
  6. 清除画布并重新绘制保存的图像.
  7. 结果:globalAlpha和globalCompositing协调工作!

这是代码和小提琴: http://jsfiddle.net/utttk/1/

ctx.fillStyle="red";
ctx.globalCompositeOperation="xor";
ctx.fillRect(0,0,200,200);
ctx.fillRect(170,0,30,30);
var png=canvas.toDataURL();
ctx.globalCompositeOperation="source-over"; // "normal" compositing
ctx.globalAlpha=.2;
var image=new Image();
image.onload=function(){
   ctx.clearRect(0,0,canvas.width,canvas.height);
   ctx.drawImage(image,0,0);
}
image.src=png;

这篇关于当形状部分透明时,如何在Canvas中从另一个形状(XOR)切出一个形状?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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