views:

212

answers:

2

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?

+2  A: 

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.

brainjam
the problem is that I am writing a plugin for flot, and the border of the plot as well as other elements on the plot has already been drawn before my plugin is called, and so clip() will not work as, from what I understand, it only prevents drawing, and does not remove. If this were not the case, this would be the perfect solution.
nsw1475
@nsw1475, I've added a second method that I think does what you want.
brainjam
+1  A: 

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();
nsw1475