Nilzone-
Nilzone-

Reputation: 2786

load image and then animate it with canvas/javascript

I'm completely new when it comes to canvas. I'm trying to draw an image onto the canvas and then animate it. Right now I'm having trouble drawing the image on screen. The image doesn't show at all.

Here part of the code:

var car = new Image();
car.src = "http://i.imgur.com/8jV4DEn.png";
car.x = 40; car.y = 60;

function draw(){
    ctx.drawImage(car.src, car.x, car.y);
}

Full fiddle here

Thanks!

Upvotes: 1

Views: 2621

Answers (1)

user1693593
user1693593

Reputation:

There are several issues with the code.

  • You have no onload handler
  • You are using x and y properties on the image element - these are read-only properties
  • You are using the image element instead of a custom object to add properties
  • You are intending to call draw instead of animate
  • You are not clearing the background of the canvas for each draw
  • You are trying to draw the image using its url
  • The poly-fill should be outside the loop
  • The reqAnimFrame poly doesn't acknowledge non-prefixed requestAnimationFrame.
  • And the car goes side-ways.. :-)

Here is adjusted code and a modified fiddle:

var reqAnimFrame = 
    window.requestAnimationFrame ||
    window.mozRequestAnimationFrame || 
    window.webkitRequestAnimationFrame || 
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame;

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');

c.height = window.innerHeight;
c.width = window.innerWidth;

var car = new Image();

/// when image is loaded, call this:
car.onload = animate;

/// x and y cannot be used, in "worse" case use this but ideally
/// use a custom object to set x and y, store image in etc.
car._x = 40;
car._y = 60;
car.src = "http://i.imgur.com/8jV4DEn.png";

var speed = 5;

function animate(){

    car._y += speed;

    draw();
    reqAnimFrame(animate);
}

function draw(){

    /// clear background
    ctx.clearRect(0, 0, c.width, c.height);

    /// cannot draw a string, draw the image:
    ctx.drawImage(car, car._x, car._y);
}

/// don't start animate() here
//animate();

Upvotes: 3

Related Questions