简体   繁体   中英

HTML5 canvas dirty rectangle Buggy Issue

I am using dirty rectangles to animate a tank go around a map. For fair game-play, the tank's torso can travel only in the cardinal directions and it's top cannon (separate from the torso, but attached to it) can also rotate in the cardinal directions.

The issue is that when I use clearRect, it may clear other objects, and obstacles immediate to it. clearRect is called as the tank moves in the certain velocity. Is it possible (without any premade physicsEngine / extermal Gitub API I have to lean), to animate the tank such that, it doesn't clear objects around it?

I've tried multiple canvases too.. How would I overlay multiple canvases, so the animation still shows, but the clearRect in one doesn't affect any object in the other?

Image of sample issue:
http://imgur.com/MPQwDAK

There are two (common) options:

  1. Draw the tanks only on a separate canvas so when you clear a tank only that canvas is affected. You can overlay canvases using fixed or absolute positioned elements.
  2. Use a single canvas but redraw everything. You can make the redraw more efficient by using a clipping mask for the region you want to redraw.

1) To overlay canvases:

<div id="canvasContainer">
    <canvas id="canvas1" ... ></canvas>
    <canvas id="canvas2" ... ></canvas>
</div>

CSS:

#canvasContainer {
    position:relative;
}
#canvasContainer > canvas {
    position:absolute;
    left:0;
    top:0;
}

2) To set a clipping mask:

ctx.clearRect(x, y, w, h);
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.save();
ctx.clip();

/// redraw everything, only clipped region will be updated

ctx.restore();

Of course, if your code/setup allow you can just redraw the area inside the regions you cleared instead of everything but if this is possible depends entirely on the draw logic you have implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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