简体   繁体   中英

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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