Jeremy Simms
Jeremy Simms

Reputation: 51

Problems clearing canvas when animating a clipping region

I'm trying to accomplish an effect similar to what you might see on the cartoon Chowder (example link) , where shapes serve as masking layers for a texture underneath that stays static. I've begun playing around with this idea by creating a render loop that clears the canvas, saves it's state, then draws a rectangular clipping region, followed by drawing the background texture that occupies the entire width and height of the canvas.

Here's the draw function:

function draw() 
{
    context.clearRect(0,0, 640, 480);
    context.save();
    x += velocityX;
    y += velocityY;
    context.rect(x, y, 40, 40);
    context.clip();
    context.drawImage(image, 0,0, 640, 480);
    context.restore();
}

Basically it just runs at 60 frames per second, updating the position of the rectangle and clipping a background image inside the clipping region. (I know the code isn't structured perfectly, but I was just experimenting to see if this effect was even possible on the canvas).

http://jsfiddle.net/JERje/86/

The problem I seem to be having is that the clipping area from the previous iteration of the loop hangs around creating the weird effect that you see in the fiddle above. I've tried reordering everything in the draw() step of the loop, but the only thing that seems to work is the canvas.width = canvas.width trick for clearing the screen. I'd like to avoid this method of clearing the screen, since it doesn't seem to work in IE, and it also destroys the canvas state. clearRect() should work to clear the screen. What am I doing wrong?

Upvotes: 0

Views: 678

Answers (2)

Jeremy Simms
Jeremy Simms

Reputation: 51

So, feel pretty dumb about this, but apparently when you call rect() you also have to make sure to call closePath afterwards in order to close the clipping area. Glad I figured it out finally, now on to adding multiple layers!

Here's the working fiddle: http://jsfiddle.net/JERje/129/

Upvotes: 1

Jack Franzen
Jack Franzen

Reputation: 778

You're using the same HTML5 Canvas paperback I am aren't you.

If you set up an adhoc canvas as I did on your jsfiddle like so:

var newCanvas = document.createElement('canvas');
newCanvas.getContext("2d").drawImage(image,0,0);

A function such as this would be able to hack a section out of that canvas:

context.putImageData(newCanvas.getContext("2d").getImageData(x,y,40,40),x,y);    

Thus giving you the chowder effect. Good show man, good luck. Pst me if it doesn't work

EDIT: However this solution will ignore some context scaling transformations. Just be smart about how you handle scale on your own (and you really should be anyways if you want the true "chowder" effect)

Upvotes: 1

Related Questions