简体   繁体   中英

to position the canvas over the <img> element

i would like to position the canvas provided by html5 over an image element using css. But I am not able to place the canvas on the image. Can you please help me out in this?

Try:

HTML

<div id="container">
    <img ...>
    <canvas ...>
</div>

CSS

#container {
    position:relative;
}
#container > img,
#container > canvas {
    position:absolute;
    left:0;
    top:0;
}

Optionally set the background loading the image with CSS instead:

canvas {
    background:url(yourImage.png);
}

or draw the image directly into canvas using JS:

var img = new Image,
    ctx = documment.getElementById('canvasId').getContext('2d');

img.onload = function() {
    ctx.drawImage(this, 0, 0);
    /// continue from here...
}
img.src = 'yourImage.png';

If both images have the same size, an alternative solution would be to only create a canvas image, but no HTML image. In the Javascript code load the "background" image and render it into the canvas, before rendering your decorations:

Drawing Images into Canvas Tutorial

This way your DOM stays simpler and you could actually "interact" with the background image pixels.

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