简体   繁体   English

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

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

I'm making a guy in which I have objects to move, each objects has an image attached to it, but I have no idea how I could move them from the center and not the left upper corner. 我正在创建一个要在其中移动对象的家伙,每个对象都有一个要附加的图像,但是我不知道如何从中心而不是从左上角移动它们。

This is the player: 这是玩家:

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';
};

And its method "Move": 及其方法“移动”:

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

I don't know where you're drawing this image, but I would use what you already have and simply draw the image in a different position. 我不知道您要在何处绘制此图像,但是我会使用已经拥有的内容,只是将图像绘制在不同的位置。

You can draw the image around your position (with Player.pos_x and Player.pos_y as a central point, rather than top left) by taking off half the image dimensions from the initial position like so: 您可以通过从初始位置取一半图像尺寸来围绕位置绘制图像(使用Player.pos_xPlayer.pos_y作为中心点,而不是左上角),如下所示:

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

In actual code this would look something like: 在实际代码中,这看起来像:

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); 

This way your Player.pos_x and Player.pos_y remain in the same position, but the image will be drawn "around" that center. 这样,您的Player.pos_xPlayer.pos_y保持在同一位置,但是图像将在该中心“周围”绘制。

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

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