我试图将图像嵌入画布中,以便可以使用画布在图像上绘制线条。但是,我似乎无法使图像显示在画布中。这是我的代码(HTML然后是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);
非常感谢您的帮助!
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 theimg
element to draw it once the image has loaded.The other issue might be that since the
img
element is set todisplay: 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.