JavaScript 使用可变参数时 drawImage 加载问题

JavaScript drawImage load issues when using variable parameters

我正在学习 'Making Isometric Real-Time Games with HTML5, CSS3 and Javascript' 中的代码教程。不幸的是,代码似乎在使用变量作为参数绘制图像时出现问题。

  var logoImg = new Image();

  // We want to resent the image so that it fills 50% of the browser window 
  // while maintaining its width/height aspect ratio
  var originalWidth = logoImg.width;
  logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
  logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);

  var logo = {
    img: logoImg,
    x: (canvas.width/2) - (logoImg.width/2),
    y: (canvas.height/2) - (logoImg.height/2)
  }

  logoImg.onload = function () {
    ctx.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
  }

  logoImg.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

正在替换

ctx.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);

ctx.drawImage(logoImg, 1, 1, 100, 100);

修复了问题。我的想法是否正确,因为在计算变量之前调用了 onload() 函数,所以它没有正确加载?如果是这样,我如何使用这些变量正确加载图像?谢谢。

ctx.drawImage(logoImg, 1, 1, 100, 100); 这解决了问题,只是因为您手动设置了维度。主要问题在这里:

var originalWidth = logoImg.width;

您还没有 logoImg.widthheight 因为图像尚未加载。

这里是完整的更正示例 (here a working example):

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');

var logoImg = new Image();

var logo = {
    img: logoImg,
    x: (canvas.width/2) - (logoImg.width/2),
    y: (canvas.height/2) - (logoImg.height/2)
}

logoImg.onload = function () {
    var originalWidth = logoImg.width;
    logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
    logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);
    //debugger;
    ctx.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);
}

logoImg.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';