我试图将 svg 图像在画布中居中,但是图像转到右下角,我不明白我做错了什么。
注意:该图像是 svg 图像,我尝试使用 png 图像,它可以工作,但是 svg 图像会引发问题。
这是我尝试过的代码
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();
});
看起来您的代码的问题可能是图像加载的时间及其位置的计算。当您在 Game 类的构造函数中计算 this.x 和 this.y 时,图像可能尚未加载,因此 this.image.width 和 this.image.height 可能仍为 0。这意味着 this.x 和this.y 被设置为画布的中心,这就是为什么图像在加载并获取其实际大小后出现在右下角的原因。