繁体   English   中英

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

[英]load image and then animate it with canvas/javascript

在画布上我是全新的。 我正在尝试将图像绘制到画布上,然后对其进行动画处理。 现在我无法在屏幕上绘制图像。 图像根本不显示。

这里是部分代码:

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);
}

在这里完全小提琴

谢谢!

代码有几个问题。

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

这是调整后的代码和修改过的小提琴

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM