gpt4 book ai didi

javascript - 在 HTML 中使用 Canvas 处理 Sprite 加载

转载 作者:行者123 更新时间:2023-11-30 18:17:10 25 4
gpt4 key购买 nike

所以我尝试使用 Canvas 编写一个简单的 Sprite 加载方法,但我注意到刷新率很糟糕。这是我正在使用的绘制方法。

function DrawSprite(context,
drawX,
drawY,
drawH,
drawW,
spriteXIndex,
spriteYIndex,
spriteW,
spriteH,
image){
var imageObj = new Image();
imageObj.onload = function() {
//draw cropped image
var sourceX = (spriteXIndex * spriteW);
var sourceY = (spriteYIndex * spriteH);

context.drawImage(imageObj, sourceX, sourceY, spriteW, spriteH, drawX, drawY, drawW, drawH);
};
imageObj.src = image;

每当调用它时,我都会看到非常明显的图像重绘。我考虑过几个解决方案,但我不确定实现它们的最佳方法。首先是双缓冲区。但是我不确定除了创建第二个 Canvas 并将其绘制在下面并使用 z-index 处理交换之外如何实现它。另一个是存储图像,而不是每次我想绘制 Sprite 时都重新创建它。我将首先尝试第二种方法并在启动程序之前预加载图像,但我希望获得有关处理此问题的最佳方法的意见。

最佳答案

您似乎在做的是创建一个新图像并每次都从源加载它,这肯定会导致性能问题。处理它的最佳方法是在保存并重新使用图像后加载图像。下面是一个非常简单的例子。 fiddle 在加载部分有点复杂,因为我从服务加载图像 http://retroships.com

function Sprite(options){
this.load(options.imagePath);
this.x = 0;
this.y = 50;
this.isLoaded = false;
}

Sprite.prototype.load = function(imagePath){
this.image = new Image();
var that = this;

this.image.src = imagePath;

this.image.onload = function(){
that.isLoaded = true;
}
}

Sprite.prototype.draw = function(){
ctx.drawImage(this.image, this.x, this.y);
}

// to use, you can pass other params and handle them like x/y/width/height what have you.
var yourSprite = new Sprite({imagePath : "pathtoimage.png"});

function render(){
if(yourSprite.isLoaded){
canvasContext.drawImage(yourSprite.image, yourSprite.x, yourSprite.y);
}
}

Working Demo

关于javascript - 在 HTML 中使用 Canvas 处理 Sprite 加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com