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

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

本文关键字:图像 获取 Javascript      更新时间:2023-09-26

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

这就是玩家:

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保持在同一位置,但图像将"围绕"该中心绘制。