【问题标题】:load image and then animate it with canvas/javascript加载图像,然后使用 canvas/javascript 对其进行动画处理
【发布时间】:2013-11-15 13:11:04
【问题描述】:

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

这里是部分代码:

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

谢谢!

【问题讨论】:

    标签: javascript html animation canvas


    【解决方案1】:

    代码有几个问题。

    • 你没有onload处理程序
    • 您正在图像元素上使用 xy 属性 - 这些是只读属性
    • 您正在使用图像元素而不是自定义对象来添加属性
    • 您打算致电draw 而不是animate
    • 您没有为每次绘制清除画布背景
    • 您正在尝试使用其 url 绘制图像
    • 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();
    

    【讨论】:

    • 不幸的是,它没有用 - 介意让我使用我包含的小提琴吗? :)
    • @Nilzone- 请查看更新后的答案,与小提琴相比,该帖子有点误导:)
    • 非常感谢你的超清晰回答:) 我还有很多东西要学
    • 顺便说一句 - 为什么我不应该调用 animate()?我查看了一些具有绘图和动画功能的指南。开始它所有 animate() 被调用。即tutorials.jenkov.com/html5-canvas/animation.html
    • @Nilzone-没问题。不要直接调用animate,因为您的图像当时没有加载(图像加载在 JavaScript 中是异步的)。这就是为什么你把它交给onload 处理程序(它会在图像加载并可以使用时调用它)。另请参阅我在答案中的更新 - 我发现 requestAnimationFrame 多边形的另一个错误。
    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    相关资源
    最近更新 更多