简体   繁体   中英

How do I embed an image on a canvas (HTML/JS)

I am trying to embed an image into a canvas so that I can draw lines over the image with the canvas. However, I can't seem to get the image to appear inside the canvas. Here's the code I have (HTML then JS):

<canvas id="myCanvas"  style="border:1px solid #d3d3d3; position: relative; z-index:3; top:10em; width: 30em; height: 20em; left: 22em;"></canvas>
    <img src="mapfinal.png" id="mapPic" style="display: none;"/>

javascript

        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        var map = document.getElementById("mapPic");
        ctx.drawImage(map, 20, 20);

Thank you so much for any help!

It could be one of two things. The most likely issue is that the image is not yet loaded before you try to draw it. To fix this, add an onload event listener to the img element to draw it once the image has loaded.

<img src="mapfinal.png" id="mapPic" onload="drawCanvas" style="display: none;"/>

<script>
function drawCanvas() {
  var c = document.getElementById("canvas");
  var ctx = c.getContext("2d");
  var map = document.getElementById("mapPic");
  ctx.drawImage(map, 20, 20);
}
</script>

The other issue might be that since the img element is set to display: none the browser isn't loading the image at all . Depending on the browser it may or may not load it. If you don't want the image to dispaly a better approach would be to create it through JavaScript.

var map = new Image();
map.onload = function() {
  var c = document.getElementById("canvas");
  var ctx = c.getContext("2d");
  ctx.drawImage(map, 20, 20);
};
map.src = 'mapfinal.png';

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