简体   繁体   English

如何在 canvas (HTML/JS) 上嵌入图像

[英]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.我正在尝试将图像嵌入到 canvas 中,以便我可以使用 canvas 在图像上绘制线条。 However, I can't seem to get the image to appear inside the canvas.但是,我似乎无法让图像出现在 canvas 中。 Here's the code I have (HTML then JS):这是我的代码(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 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元素添加一个onload事件侦听器,以便在图像加载后绘制它。

<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 .另一个问题可能是由于img元素设置为display: none 浏览器根本没有加载图像 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.如果您不希望图像显示更好的方法是通过 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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM