Srujan Barai Srujan Barai - 5 months ago 8
HTML Question

html5: Show an image OVER the canvas

I was trying to implement the new

html5
canvas
tag.

I made a Board for a game using that canvas. Now I wanted to add pawns to the game. I can add an image to canvas using
ctx.drawImage()
method of canvas, but that actually prints the image on the canvas.

I wanted the pawn to be drawn over the board (theoretically like a layer on it) so that I can move it. I tried this code to add an image using just javascript.

function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;

document.body.appendChild(img);
}


But that didnt help. I can guess that this function just "adds" an element to the body of the main
html
file and that could be the reason why the image is not shown on the page.

Can anybody help me know how can draw an image over the canvas? Any help will be appreciated!

Feel free to suggest edits.

Answer

you can simply use two canvases, with absolute positions, where one canvas is over the other canvas, e.g.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

in layer 1 you can show board, and in layer2 you can show pawns..

Comments