Skip to content

Month: June 2011

HTML5: CSS Sprites

See the demo.

 
<!doctype html> 
<html> 
<head> 
	<style type="text/css"> 
		.sprite {
			background:url(sheet.png);
			width:32px;
			height:48px;
		}
 
		.up { background-position-y: -7px;}
		.down { background-position-y: -102px;}
		.right { background-position-y: -55px;}
		.left { background-position-y: -151px;}
 
		.frame0 { background-position-x: -0px;}
		.frame1 { background-position-x: -36px;}
		.frame2 { background-position-x: -73px;}
		.frame3 { background-position-x: -107px;}
	</style> 
 
	<script type="text/javascript"> 
var counter=0;
setInterval(main_loop, 250);
function main_loop(){
  counter = (counter+1) % 3; // 0,1,2,3,0,1,2 ...
  document.getElementById("up").setAttribute("class", "sprite up frame"+counter);
  document.getElementById("down").setAttribute("class", "sprite down frame"+counter);
  document.getElementById("right").setAttribute("class", "sprite right frame"+counter);
  document.getElementById("left").setAttribute("class", "sprite left frame"+counter);
}
</script> 
 
	<meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
	<title>CSS Sprites + JavaScript </title> 
</head> 
 
<body> 
	<img id="up" src="transparent.gif" /> 
	<img id="down" src="transparent.gif" /> 
	<img id="right"	src="transparent.gif" /> 
	<img id="left" src="transparent.gif" /> 
	<p>— We are not gifs!</p> 
</body> 
</html>

Credits and notes:

simple HTML5 animation: clouds over background

If you are reading this text, sorry, your browser don’t support HTML5 Canvas (or maybe I did something wrong).

Code:

var canvas;
var ctx;
 
var background;
var width = 300;
var height = 200;
 
var cloud;
var cloud_x;
 
function init() {
	canvas = document.getElementById("cloud_demo_canvas");
	width = canvas.width;
	height = canvas.height;
	ctx = canvas.getContext("2d");
 
	// init background 
	background = new Image();
	background.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/forest.png';
 
	// init cloud
	cloud = new Image();
	cloud.src = 'http://silveiraneto.net/wp-content/uploads/2011/06/cloud.png';
	cloud.onload = function(){
		cloud_x = -cloud.width;
	};
 
	return setInterval(main_loop, 10);
}
 
function update(){
	cloud_x += 0.3;
	if (cloud_x > width ) {
		cloud_x = -cloud.width;
	}
}
 
function draw() {
	ctx.drawImage(background,0,0);
	ctx.drawImage(cloud, cloud_x, 0);
}
 
function main_loop() {
	draw();
	update();
}
 
init();

HTML code:

<canvas id="cloud_demo_canvas" width="640" height="480">Alternative text if browser don't support canvas.</canvas>

Credits and notes: