HTML5 Canvas Sprite Blitting

Wed, 06/07/2017 - 22:23

Canvas HTML5 Blitting

This is a simple demonstration of sprite blitting using HTML5 canvas and Javascript.

I don't think I would suggest this method. It's some old code I wrote several years ago. But, I'm just re-posting some old content intermingled with new content. I will likely post an updated version of this with more modern methods.

This uses sprites from an old game Thog and Jeff I worked on several years ago.

var max_frame = 11600;
var img = "/sites/default/files/2017-06/walk_left.gif";

var sx = 0;
speed = 25;
bool = false;
function walk() {
    var a_canvas = document.getElementById("canvas_jeff");
    var a_context = a_canvas.getContext("2d");
    var jeff = new Image();
    jeff.src = img;
    jeff.onload = function() {
        a_canvas.width = a_canvas.width;
        a_context.drawImage(jeff,sx,0,400,300,0,0,400,300); 
        sx+=400;
        if( sx >= max_frame ){ sx = 0; }
        if(bool){setTimeout(walk,speed);}
    }
}
function left() {
	max_frame = 11600;
	img = "/sites/default/files/2017-06/walk_left.gif";
	if(!bool)start();		
}
function right() {
	max_frame = 11200;
	img = "/sites/default/files/2017-06/walk_right.gif";
	if(!bool)start();
}
function stop() {
	bool = false;
	console.log("stopped");
}
function start() {
	console.log("started");
	bool = true;
	walk();
}
function showValue(newValue) {
	speed = document.getElementById("range").innerHTML=newValue;
}

 

Set the animation speed
( Chrome & Safari only )
25