简体   繁体   English

在HTML画布中的形状下清除像素

[英]clear pixels under a shape in HTML canvas

I am using an HTML canvas and javascript and I need to clear all of the pixels underneath a shape created by closing a path (for example, I am using flot , and I want to make rounded corners, and to do this, I first need to remove the square corners by drawing a curve on top of the corner to remove the desired pixels). 我正在使用HTML画布和javascript,我需要清除通过关闭路径创建的形状下面的所有像素(例如,我使用flot ,我想要制作圆角,为此,我首先需要通过在角落顶部绘制曲线以移除所需的像素来移除方角。

Right now, I am doing this by just filling the shape with the same color as the background, which can imitate what I want to do, but, it is not ideal as it makes it impossible to place the chart on top of non-solid backgrounds without seeing the square corners. 现在,我这样做只是填充与背景相同颜色的形状,这可以模仿我想要做的事情,但是,它不理想,因为它使得无法将图表置于非固体之上没有看到方角的背景。 I know that there is a clearRect method that would do what I want to do, but with only rectangles, I need to do it with any closed shape. 我知道有一个clearRect方法可以做我想做的事情,但只有矩形,我需要用任何封闭的形状来做。 Is it possible, and if so, how would I do it? 有可能,如果是的话,我该怎么做?

brainjam's code was heading in the right direction, but didn't fully solve the problem. brainjam的代码朝着正确的方向前进,但没有完全解决问题。 Here's the solution: 这是解决方案:

context.save();
context.globalCompositeOperation = 'copy';
context.fillStyle = 'rgba(0,0,0,0)';
//draw shape to cover up stuff underneath
context.fill();
context.restore();

Here's an example of a function that will clear a circle from a canvas: 这是一个从画布中清除圆圈的函数示例:

var clearCircle = function(x, y, radius)
{
    context.save();
    context.globalCompositeOperation = 'destination-out';
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI, false);
    context.fill();
    context.restore();
};

I think what you want is a clipping region , defined by the clip() function. 我想你想要的是一个剪辑区域 ,由clip()函数定义。 The latter takes a bunch of paths. 后者需要一堆路径。 Here's an example . 这是一个例子

This is a little different from what you are specifically asking (which is to remove pixels after drawing them), but actually not drawing the pixels in the first place is probably better, if I understand your requirements correctly. 这与你特别要求的(与绘制它们后删除像素)略有不同,但如果我正确理解你的要求,实际上不首先绘制像素可能更好。

Edit: I now think I understand that what you want to do is clear pixels to transparent black. 编辑:我现在认为我明白你要做的是清晰像素到透明黑色。 To do that, after having defined your paths, do something like this: 为此,在定义路径后,执行以下操作:

context.fillStyle = 'rgba(0,0,0,0)';
context.fill();

The first statement sets the fill color to transparent black. 第一个语句将填充颜色设置为透明黑色。

Use globalCompositeOperation = 'destination-out' instead of 'copy' , it will erase all pixels of the shape in the canvas. 使用globalCompositeOperation = 'destination-out'而不是'copy' ,它将擦除画布中形状的所有像素。

See all kinds of composition here 在这里查看各种组合

very usefull ! 非常有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM