I'm new to Canvas and I've started using an example of a simple linear motion animation from HTML Canvas Tutorials.
Is it possible to replace the rectangle so it displays an image instead?
Every time I've attempted editing the code the image that's outputted is static so I'm obviously doing something wrong.
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function drawRectangle(myRectangle, context) {
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height);
context.fillStyle = '#8ED6FF';
context.fill();
context.lineWidth = myRectangle.borderWidth;
context.strokeStyle = 'black';
context.stroke();
context.drawImage = 'images/player.png';
}
function animate(myRectangle, canvas, context, startTime) {
// update
var time = (new Date()).getTime() - startTime;
var linearSpeed = 200;
// pixels / second
var newX = linearSpeed * time / 1000;
if (newX < canvas.height - myRectangle.height - myRectangle.borderWidth / 2) {
myRectangle.y = newX;
}
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
drawRectangle(myRectangle, context);
// request new frame
requestAnimFrame(function() {
animate(myRectangle, canvas, context, startTime);
});
}
var canvas = document.getElementById('monopoly-piece');
var context = canvas.getContext('2d');
var img = new Image;
var myRectangle = {
x: 20,
y: 0,
width: 50,
height: 50,
borderWidth: 5,
img: 'images/player.png'
};
drawRectangle(myRectangle, context);
// wait one second before starting animation
setTimeout(function() {
var startTime = (new Date()).getTime();
animate(myRectangle, canvas, context, startTime);
}, 1000);
Any help would be much appreciated, Thanks in advance. :)