Venatu
Venatu

Reputation: 1294

Preserving part of a canvas

When drawing on a HTML5 canvas element, is it possible to leave part of it untouched? Can you take part of the image, and then redraw that part if its not directly possible?

The only solution I have thought of is to draw to a seprate, smaller canvas and then copy that over to the main canvas. Is this a feasible approach?

I wish to draw a game scene while preserving the ui. Unfortunately, the draw order is not known in advance.

Upvotes: 4

Views: 168

Answers (3)

pimvdb
pimvdb

Reputation: 154828

I guess you're looking for .clip: http://jsfiddle.net/eGjak/122/.

ctx.rect(100, 50, 200, 100);          // make a region
ctx.clip();                           // constrain to that region
ctx.drawImage($("img").get(0), 0, 0); // draw image

Upvotes: 5

Jack
Jack

Reputation: 15872

When creating Canvas games i've always layered the GUI on top of the game canvas.

#ui{position: fixed; margin-left: auto; margin-right: auto; z-index: 1000; width: 500; height: 500}
#game{position: fixed; margin-left: auto; margin-right: auto; z-index: 999}

<div id="ui"><!--UI elements--></div>
<canvas id="game" width="500" height="500"></canvas>

Obviously you can layer another canvas on top, or build the UI using html elements.

Upvotes: 0

Chris G.
Chris G.

Reputation: 3981

Draw the UI on another canvas. You can layer canvas elements if need be.

HTML

<div id="gameframe">
    <canvas id="game-ui"></canvas>
    <canvas id="game"></canvas>
</div>

CSS

#gameFrame { position: relative; width: 800px; height: 800px;}
#game-ui { position: absolute; z-index: 10; bottom: 0; left; 0; height: 50px; width: 100%;}
#game { position: absolute; z-index: 5; height: 100%; width: 100%;}

Yields

-------------------------------------------------------
-                                                     -
-                                                     -
-                                                     -
-                <canvas id="game">                   -
-                                                     -
-                                                     -
-                                                     -
-                                                     -
-------------------------------------------------------
-               <canvas id="game-ui">                 -
-------------------------------------------------------

Upvotes: 2

Related Questions