Question

Am trying to set a "dirty zone" on my canvas to prevent the repainting of unmoved items (background image, static items, etc.) i.e. only the background painted behind a moving player needs to be redrawn

EDIT: As suggested, here's the jsfiddle of it http://jsfiddle.net/7kbzj/3/

The "update" method doesn't work out there, so it's moveSprite() you can get run by clicking the "move sprite" link... Basically, the clipping zone shouldmove by 10px to the right each time you click. Clipping mask stays at initial position, only the re-paint occurs. Weird o_O

So as I init my canvas, once the background is painted, set I use the ctx.save() method:

function init() {
    canvas = document.getElementById('kCanvas');
    ctx = canvas.getContext('2d');  

    ctx.fillStyle = "rgb(0,128,0)";
    ctx.fillRect (0,0,320,240);

    ctx.save();

    setInterval(function () { update(); }, tpf);
}

In order to see the clipping works, I draw a different color background (blue one) in the area that I wanted clipped... the result is bad, only the first clipped area is painted blue :(

function update() {
    setDirtyArea(x,y,w+1,h)

    ctx.fillStyle = "rgb(0,0,128)";
    ctx.fillRect (0,0,320,240);

    x++;

    // paint image
    ctx.clearRect(x,y,w,h);
    ctx.drawImage(imageObj, x, y);

}

function setDirtyArea(x,y,w,h) {
   ctx.restore();   
   // define new dirty zone
   ctx.beginPath();
   ctx.rect(x, y, w, h);
   ctx.clip();
}

I'd love to se the blue zone propagate itself towards the right of the screen... please help, I don't understand what's wrong! Thanks, J.

Was it helpful?

Solution

You need to wrap the actual drawing and clipping of the box with the save and restore methods. and include the closePath method. I have modified your fiddle to work the way I believe you are trying to make it.

http://jsfiddle.net/jaredwilli/7kbzj/7/

ctx.save(); // save the context
    // define new dirty zone
    ctx.beginPath();
        ctx.rect(x, y, w, h);
        ctx.clip();

ctx.restore(); // restore the context

I also have learned that using save and restore can get really complex, and confusing to know which context your in. It came up with a pretty huge canvas app im working on, and i found that indenting your canvas code helps immensely. Especially the save/restores. I have even decided it should be considered a best practice, so the more people who know and do it the better.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top