【问题标题】:How can I draw my character in the middle of my mouse click coordinates, not to the upper left?如何在鼠标点击坐标的中间而不是左上角绘制我的角色?
【发布时间】: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

【问题讨论】:

  • 只需将光标的widthheight的一半分别添加到xy即可。
  • 你的意思是头像的图片大小,对吧?如图所示,我已经尝试过了,我很奇怪为什么它不起作用。更奇怪的是,当我减去一半的图像大小时,字符会向右移动到光标的中间。 o_O
  • 嗯。图像以这种方式绘制,其左上角出现在指定坐标处。因此,是的,您需要从点击位置减去 avatar 宽度/高度的一半。

标签: javascript html


【解决方案1】:

,不加,宽度和高度的一半:

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, centerX, centerY, this.avatarWidth, this.avatarHeight);
}; // end draw fxn

【讨论】:

  • 德普。我不知道为什么我今天没有好好思考。你知道你需要在编码时休息一下......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-20
  • 2021-06-05
  • 2016-10-29
  • 2010-11-23
  • 1970-01-01
相关资源
最近更新 更多