So I’m attempting to write a simple sprite loading method using a canvas, and im noticing a terrible refresh rate. This is the draw method I’m using.
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;
}
When ever this is called i get a very noticeable redraw of the image. I’ve thought about a couple solutions but I’m not sure the best method of implementing them. First is a double buffer. But im not sure how to implement that other than creating a second canvas and drawing it underneath and handle the swap using z-index. The other is storing the images and not recreating it every time I want to draw a sprite. I’m going to try the second method first and preload the images before I start the program, but I was hoping for input regarding the best way to handle this.
What you seem to be doing is creating a new image and loading it from the source everytime which will definitely cause performance issues. The best way to handle it is to load the image once save and reuse it. Below is a very simple example. The fiddle is a little more complex on the loading portion since Im loading an image from a service http://retroships.com
Working Demo