Sprite drawing
by Raul Bojalil
HTML
<canvas width=1000 height=1000 id="canvas"></canvas>
<image style="display: none" id="image" src="https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Forig01.deviantart.net%2Fd159%2Ff%2F2008%2F127%2Fc%2Fe%2Fvg_tails_sprite_by_vg_tails.jpg" />
JavaScript
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var ctx = canvas.getContext('2d');
var x = 200;
var y = 200;
var w = 50;
var h = 50;
var rotation = 0;
var opacity = 0;
var speedX = 0.1;
var speedY = 0.1;
function drawSprite(image, x, y, w, h, sx, sy, sw, sh, flipped, rotation, opacity) {
rotation = rotation || 0;
ctx.globalAlpha = opacity;
ctx.setTransform(flipped ? -1 : 1,0,0,1,x+(w/2),y+(h/2));
ctx.rotate(flipped ? rotation * -1 : rotation);
ctx.drawImage(image,
sx, sy, sw, sh,
(-w/2), (-h/2), w, h);
ctx.setTransform(1,0,0,1,0,0);
ctx.globalAlpha = 1;
}
function drawRect(x,y,w,h, color, rotation){
ctx.setTransform(1,0,0,1,x+(w/2),y+(h/2));
ctx.rotate(rotation);
ctx.fillStyle = color;
ctx.fillRect((-w/2),(-h/2),w,h);
ctx.setTransform(1,0,0,1,0,0);
}
function update(diff) {
if (diff < 0 || isNaN(diff)) return;
rotation += 0.001 * diff;
opacity += 0.001 * diff;
x += speedX * diff;
y += speedY * diff;
if (opacity > 1) opacity = 0;
if (x > 500 && speedX > 0) {
speedX *= -1;
}
if (x < 0 && speedX < 0) {
speedX *= -1;
}
if (y > 300 && speedY > 0) {
speedY *= -1;
}
if (y < 0 && speedY < 0) {
speedY *= -1;
}
}
function draw(diff) {
if (diff < 0 || isNaN(diff)) return;
ctx.clearRect(0, 0, 2000, 2000);
drawRect(x, y, w, h, 'yellow', 0);
drawRect(x, y, w, h, 'red', rotation);
drawSprite(image, 0, 0, 50, 50, 0, 0, 170, 170, true, rotation, opacity);
drawSprite(image, 0, 50, 50, 50, 0, 0, 170, 170, true, rotation, opacity);
//drawRect(0, 0, w, h, 'green', 0);
//ctx.translate(x+(w/2), y+(w/2));
//ctx.restore();
}
var startTime = window.mozAnimationStartTime || Date.now();
function animate(timestamp) {
var drawStart = (timestamp || Date.now()),
diff = drawStart - startTime;
startTime = drawStart;
requestAnimationFrame(animate);
update(diff);
draw(diff);
}
animate();