【问题标题】:JavaScript object with a texture带有纹理的 JavaScript 对象
【发布时间】:2014-03-28 23:43:40
【问题描述】:

您好,我正在开发一个小型 JavaScript 游戏,我编写了一个 Object 构造函数来创建游戏的 SpaceCraft 对象。
构造函数的代码是

function SpaceCraft () {

var obj = this;

this.texture = new Image();
this.texture.src = "img/spacecraft.png";
this.texture.onload = function () {
    obj.w = this.width;
    obj.h = this.height;
}

this.x = canvasW / 2 - this.w / 2;
this.y = canvasH / 2 - this.h;

//Methods

//Draw
this.draw = function () {
    ctx.drawImage(this.texture, this.x, this.y);
}
}

在构造函数中存在两个问题:

  1. this.w 和 this.h 等于 0,尽管图像的大小不是 0x0
  2. this.x 和 this.y 等于 NaN,但它们应该是一个数字
var canvas;
var ctx;
var canvasH;
var canvasW;


window.onload = function () {
canvas  = document.getElementById("canvas");
ctx     = canvas.getContext('2d');

canvasH = 480;
canvasW = 960;

canvas.width  = canvasW;
canvas.height = canvasH;

drawCanvas();
}

这是画布功能

function drawCanvas () {

ctx.fillStyle = "#000000"
ctx.fillRect(0, 0, canvasW, canvasH);
}

构造函数有什么问题?
谢谢。

【问题讨论】:

  • 你从哪里得到canvasWcanvasH
  • 图像在加载之前不会“具有”尺寸,这是一个异步操作。
  • 图像需要在知道它的尺寸之前被加载,仅仅定义它的 src 是不够的。 this.xthis.y 可能是 NaN,因为它们是字符串值(例如 400px / 2 = NaN),但如果不了解 canvasWcanvasH 值,就很难说。
  • 对不起,我没有发布我得到canvasH和canvasW的地方,我现在发布它
  • 我已经更改了构造函数,现在宽度和高度属性很好,但属性 x 和 y 仍然等于 NaN。我该如何解决?

标签: javascript image


【解决方案1】:

图像尚未加载。这就是为什么你得到宽度和高度。使用onload 事件处理程序来设置这些参数。

我不能说为什么this.xthis.yNaN,但很可能canvasWcanvasH 没有正确定义。考虑改用ctx.canvas.widthctx.canvas.height

【讨论】:

猜你喜欢
  • 2020-04-12
  • 2013-05-06
  • 2012-12-06
  • 2020-03-09
  • 2014-05-27
  • 2015-05-17
  • 2018-01-18
  • 2015-09-06
  • 1970-01-01
相关资源
最近更新 更多