clear pixels under a shape in HTML canvas

2020-07-13 08:53发布

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).

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. Is it possible, and if so, how would I do it?

4条回答
地球回转人心会变
2楼-- · 2020-07-13 09:08

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();
};
查看更多
▲ chillily
3楼-- · 2020-07-13 09:13

brainjam's code was heading in the right direction, but didn't fully solve the problem. 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();
查看更多
等我变得足够好
4楼-- · 2020-07-13 09:15

I think what you want is a clipping region, defined by the clip() function. 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.

查看更多
孤傲高冷的网名
5楼-- · 2020-07-13 09:15

Use globalCompositeOperation = 'destination-out' instead of 'copy', it will erase all pixels of the shape in the canvas.

See all kinds of composition here

very usefull !

查看更多
登录 后发表回答