由于闪烁和性能问题,我决定尝试在班级中实现预渲染系统。
class component {
constructor(width, height, color, x, y, type) {
this.ctx = myGameArea.context;
this.color = color;
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.width = width;
this.height = height;
this.x = x;
this.y = y;
//PRERENDER--------------------------------------------------------
this.offscreenCanvas = document.createElement('canvas');
this.offscreenCanvas.width = this.width;
this.offscreenCanvas.height = this.height;
this.offscreenContext = this.offscreenCanvas.getContext('2d');
if (this.type == "image") {
this.offscreenContext.drawImage(this.image,
this.x,
this.y,
this.width, this.height);
}
}
//-------------------------------------------------------
update() {
if (this.type == "image") {
this.ctx.drawImage(this.offscreenCanvas, 0, 0);
} else {
this.ctx.fillStyle = this.color;
this.ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
当我这样创建一个简单实例时:
player = new component(100, 100, "filepath", 100, 100, "image")
并在一个简单的requestAnimationFrame()循环中运行它:
requestAnimationFrame(updateGame)
function updateGame(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
player.update();
requestAnimationFrame(updateGame);
}
对象播放器和画布仍按其正常方式运行,除了图像路径正确以外,图像不可见。我在做什么错了?