Alex
Alex

Reputation: 33

Animate moving an image in canvas

Im new to using canvas but wonder if i could get some help or advice on where to start with this. i currently have a circle drawn on canvas and have tried multiple ways i thought might work but cant get my head round it. When searching online i can only really find help where the shapes are drawn in canvas itself.

Here is what i have so far: JSFiddle

JavaScript:

var one = document.getElementById("canvOne");
var canvOne = one.getContext("2d");
var img = new Image();
img.onload = function(){
    canvOne.drawImage(img, 10, 10);
};

img.src = "img/circle.jpg";

function oneStart(){
    for(var i = 0; i < 300; i++){
        img.style.left = i + 'px';
        setTimeout(oneStart, 1000);
    }
};

can anyone give me a hand with this please?

Upvotes: 1

Views: 302

Answers (1)

Canvas
Canvas

Reputation: 5897

jsFiddle : http://jsfiddle.net/8eLL7L5L/3/

javascript

//canvas one
var one = document.getElementById("canvOne");
var canvOne = one.getContext("2d");
var img = new Image();

var animate = false;
var circlePosX = 10;
var circlePosY = 10;

img.onload = function () {
    canvOne.drawImage(img, circlePosX, circlePosY);
};

img.src = "http://www.alexvolley.co.uk/other/circle.jpg";

var start = function()
{
    animate = true;
}

var stop = function()
{
    animate = false;   
}

setInterval(function () {
    // Only update circle position if animate is true
    if (animate) {
        circlePosX += 1;
        canvOne.fillStyle = "#FFF";
        canvOne.fillRect(0, 0, one.width, one.height);
        canvOne.drawImage(img, circlePosX, circlePosY);
    }
}, 3);

All I have done is created 3 variables and added a few little functions, the circle's XPos and YPos are now stored so we can access them, I have also created a bool variable animate which is used to check if we should animate the circle.

The start function simply sets animate to true

The stop function simple sets animate to false

the setInterval just keeps running the same code over and over every 3 miliseconds, all this does is clears the canvas and then redraws the circle. If we don't clear the canvas you would see multiple circles appear when animate is true.

I hope this helped

Upvotes: 1

Related Questions