加载图像,然后使用canvas / javascript对其进行动画处理

时间:2013-11-04 19:47:37

标签: javascript html5 animation canvas

对于画布来说,我是全新的。我试图将图像绘制到画布上然后为其制作动画。现在我在屏幕上绘制图像时遇到了麻烦。图像根本没有显示。

这部分代码:

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

谢谢!

1 个答案:

答案 0 :(得分:3)

代码有几个问题。

  • 您没有onload处理程序
  • 您在图片元素上使用xy属性 - 这些是只读属性
  • 您正在使用图片元素而不是自定义对象来添加属性
  • 您打算致电draw而不是animate
  • 您没有清除每次抽奖的画布背景
  • 您正尝试使用其网址
  • 绘制图片
  • poly-fill应该在循环之外
  • reqAnimFrame poly不承认未加前缀requestAnimationFrame
  • 汽车走路......: - )

以下是经过调整的代码和 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();