JS drawImage 坏了

问题描述

图像在同一个目录中,所有东西,我似乎无法让它工作。

[[0 1 1]
 [1 0 1]
 [1 1 0]]
[[False  True False]
 [ True False False]
 [ True False False]]
[[False  True False]
 [ True False False]
 [False False False]]
[[74. nan  2.]
 [nan 73.  8.]
 [ 0. 10. 72.]]

图像显示<body> <center> <canvas id='scrn' width='100' height='100'/> </center> <script> function draw() { var cv = document.getElementById('scrn').getContext('2d'); var img = document.getElementById('image'); cv.drawImage(img,10,10 10,); } draw(); </script> <image id='image' src='test.jpg'/> </body> 标签中,但不在画布中。这是为什么?

解决方法

您需要使用回调,以便仅在图像加载后调用 boot()。 例如:

document.getElementById("image").onload = boot
,
var canvas = document.getElementById('scrn'); // get your canvas
    if (canvas) {
      var context = canvas.getContext('2d'); // get canvas context
      var img = document.getElementById('image'); // get image
      if (context && img) { // make sure context and img exists
        img.onload = () => { // call drawImage when img has finished loading
          context.drawImage(img,10,10 10,);
        }
      }
    }

我建议在 var 上使用 let 和 const。为了以后注意,请始终在图像的 onload 回调中使用 drawImage,因为这样可以确保您希望绘制的图像已成功加载。