Search code examples
javascripthtmlcanvashtml5-canvas

center image in canvas html


I'm trying to center an svg image in canvas, however the image goes to the right bottom corner, I couldn't understand what I'm doing wrong.

notice: the image is an svg image, I tried a png image it works, however an svg image start the problem.

this is the code I tried

window.addEventListener('load', function () {
     const canvas = document.querySelector('canvas');
     const context = canvas.getContext('2d');
     const CANVAS_WIDTH = (canvas.width = window.innerWidth - 100);
     const CANVAS_HEIGHT = (canvas.height = window.innerHeight - 100);

     class Game {
          constructor(gameWidth, gameHeight) {
               this.width = gameWidth;
               this.height = gameHeight;
               this.image = new Image();
               this.image.src = option.introImage;
               this.centerX = this.width / 2;
               this.centerY = this.height / 2;

               this.x = this.centerX - this.image.width * 0.5;
               this.y = this.centerY - this.image.height * 0.5;
          }

          draw(context) {
               context.drawImage(this.image, this.x, this.y);
          }

          update() {}
     }

     const game = new Game(CANVAS_WIDTH, CANVAS_HEIGHT);

     function animate() {
          game.update();
          game.draw(context);
          requestAnimationFrame(animate);
     }
     animate();
});

Solution

  • It looks like the issue with your code may be the timing of the image loading and the calculation of its position. When you calculate this.x and this.y in the constructor of your Game class, the image might not have loaded yet, so this.image.width and this.image.height are likely still 0. This means that this.x and this.y are being set to the center of the canvas, which is why the image appears in the bottom right corner once it loads and gets its actual size.