繁体   English   中英

如何获取Javascript中图像的中心?

[英]How do I get the center of an Image in Javascript?

我正在创建一个要在其中移动对象的家伙,每个对象都有一个要附加的图像,但是我不知道如何从中心而不是从左上角移动它们。

这是玩家:

function Player() {
    this.height = 167.5;
    this.width = 100;
    this.pos_x = 350;
    this.pos_y = 425;
    this.player_image = new Image();
    this.player_image.src = 'img/player_car_img.png';
};

及其方法“移动”:

Player.prototype.move = function(){
    if (37 in keysDown) {
        this.pos_x -= 10;
    }  else if (39 in keysDown) {
        this.pos_x += 10;
    }
};

我不知道您要在何处绘制此图像,但是我会使用已经拥有的内容,只是将图像绘制在不同的位置。

您可以通过从初始位置取一半图像尺寸来围绕位置绘制图像(使用Player.pos_xPlayer.pos_y作为中心点,而不是左上角),如下所示:

Y = Y location - (image height / 2)
X = X location - (image width / 2)

在实际代码中,这看起来像:

var x = Player.pos_x - Player.player_image.width/2;
var y = Player.pos_y - Player.player_image.height/2;
ctx.drawImage(Player.player_image, x, y); 

这样,您的Player.pos_xPlayer.pos_y保持在同一位置,但是图像将在该中心“周围”绘制。

暂无
暂无

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

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