【发布时间】:2012-04-25 08:31:27
【问题描述】:
我有一个游戏,您可以在其中单击 2D HTML5 画布来设置角色移动到的点。当我点击时,我注意到角色会出现在鼠标点击位置的右下角。所以我假设 context.drawImage() 的 x,y 坐标参数用于从哪里开始绘制图像的左上角。根据这个规范,我是对的:http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#drawing-images-to-the-canvas
我尝试通过在 centerX 和 centerY 处绘制来调整它,如下所示。我似乎得到了与上述类似的结果。嗯?我该怎么办?
这是我的角色类绘制函数,由在计时器上运行的 update() 调用。
this.Draw = function () {
// var centerX = this.currentX + (this.avatarWidth/2);
// var centerY = this.currentY + (this.avatarHeight/2);
// console.log("hermes' supposed draw location = " + centerX + "," + centerY + " | currentX,Y = " + this.currentX + "," + this.currentY);
// console.log("currentX,Y = " + this.currentX + "," + this.currentY);
context.drawImage(hermesAvatar, this.currentX, this.currentY, this.avatarWidth, this.avatarHeight);
}; // end draw fxn
【问题讨论】:
-
只需将光标的
width和height的一半分别添加到x和y即可。 -
你的意思是头像的图片大小,对吧?如图所示,我已经尝试过了,我很奇怪为什么它不起作用。更奇怪的是,当我减去一半的图像大小时,字符会向右移动到光标的中间。 o_O
-
嗯。图像以这种方式绘制,其左上角出现在指定坐标处。因此,是的,您需要从点击位置减去 avatar 宽度/高度的一半。
标签: javascript html