繁体   English   中英

JavaScript图片无法绘制到画布

[英]JavaScript Image not drawing to canvas

我只是一个完整的菜鸟,一直在寻找答案。 “ctx.fillRect(0,0,100,100);” 表示ctx已正确声明并且正在调用“ test()”的工作。 我只是不明白为什么这张图不会画出来。

var Img = new Image();
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag

function test(){
    ctx.fillStyle = 'blue';
    ctx.fillRect(0,0,100,100);  //THIS WORKS
    ctx.drawImage(Img,0,0,600,600); // Will not load
}
Img.scr ='/client/Assets/StartScreen/Background.png'; //This URL was tested via html img tag

Img.scr未定义的属性。 您应该尝试使用Img.src

Img.src ='/client/Assets/StartScreen/Background.png';

两件事情:

  • 您的代码img.scr ,而不是img.src
  • 图像加载异步进行; 您需要等待图像完成( img.complete )。 您可以使用onload事件侦听器在图像准备就绪后立即绘制内容。

var img = new Image();
img.src = "/client/Assets/StartScreen/Background.png";

function draw() {
  ctx.fillStyle = "blue";
  ctx.fillRect(0, 0, 100, 100);
  ctx.drawImage(img, 0, 0, 600, 600);
}

img.onload = function() {
  draw();
};

仅应在加载图像时将其添加到画布。 尝试,

var Img = new Image();
Img.src ='/client/Assets/StartScreen/Background.png'; 
Img.onload = function() {
      test();
 }

function test(){
    ctx.fillStyle = 'blue';
    ctx.fillRect(0,0,100,100);  
    ctx.drawImage(Img,0,0,600,600); 

}

暂无
暂无

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

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