2013-11-04 30 views

回答

2

代码有几个问题。

  • 你没有onload处理
  • 您正在使用的图像元素xy性能 - 这是只读属性
  • 您正在使用的图像元素,而不是一个自定义对象添加属性
  • 你打算叫draw代替animate
  • 您还没有清空画布的每个画
  • 背景
  • 您正在试图利用其网址
  • 聚填充应该是循环
  • reqAnimFrame聚不承认非前缀​​外绘制的图像。
  • 和车去副作用的方法.. :-)

这里是调整代码和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(); 
+0

它没有工作,不幸的是 - 用小提琴给我看包括我? :) –

+0

@ Nilzone-请参阅更新的答案,该帖子有点误导相比,小提琴:) – K3N

+0

非常感谢你的超清晰答案:)我仍然有很多东西要学会 –