简体   繁体   中英

Image not positioned correctly in a Canvas

As you can see here: https://codepen.io/Le-future/pen/gKNoEE

I have a slight problem with the images as they are not centered in the circles, is someone could help?

    ctx.beginPath();
    ctx.arc(object.x, object.y, object.size/1.25, 0,2*Math.PI);
    ctx.fillStyle = object.couleur;
    ctx.fill();
    ctx.restore();

    ctx.drawImage(object.image, object.x, object.y, object.size, object.size);

Change: ctx.drawImage(object.image, object.x, object.y, object.size, object.size);

To this: ctx.drawImage(object.image, object.x-object.size/2, object.y-object.size/2, object.size, object.size);

Why? You're not taking the width and height of the object into account to center it. The x and y positions are located in the top left of the object, so subtracting those points by 1/2 of its width and height centers it.

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