Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript我想使用let img=new Image();在浏览器上显示图像的步骤_Javascript_Html - Fatal编程技术网

Javascript我想使用let img=new Image();在浏览器上显示图像的步骤

Javascript我想使用let img=new Image();在浏览器上显示图像的步骤,javascript,html,Javascript,Html,这是html的一部分 这是javascript文件(test.js) let cvs=document.getElementById('canvas'); 设ctx=cvs.getContext('2d'); 设bg=newimage(); bg.src='earth.png'; 函数绘图(){ ctx.drawImage(bg,0,0); } draw(); earth.png未在Chrome上显示。我找不到错误 我使用vscode对其进行编码。我确认文件earth.png,test.j

这是
html
的一部分


这是javascript文件(test.js)

let cvs=document.getElementById('canvas');
设ctx=cvs.getContext('2d');
设bg=newimage();
bg.src='earth.png';
函数绘图(){
ctx.drawImage(bg,0,0);
}
draw();
earth.png
未在Chrome上显示。我找不到错误

我使用
vscode
对其进行编码。我确认文件
earth.png
test.js
test.html
位于同一文件夹中


我使用
vscode
extension
Live Server
查看chrome中会显示什么。

在图像加载之前不能调用drawImage()方法。
-

let cvs=document.getElementById('canvas');
设ctx=cvs.getContext('2d');
设bg=newimage();
bg.src='earth.png';
函数绘图(){
ctx.drawImage(bg,0,0);
}
bg.onload=牵引;

在绘制图像之前,必须等待图像加载。查看onload属性。我发现在一些教程中可以运行相同的代码,为什么?可能他们使用了数据URI?我不知道。但在绘制之前,必须等待图像加载。请参见此处的示例: