Simply canvas animation

前端 未结 2 1246
北恋
北恋 2021-01-25 00:23

I have a simple canvas animation: two rectangles move in two different directions. However, I feel this could be simplified more.

http://jsfiddle.net/tmyie/R5wx8/6/

2条回答
  •  清酒与你
    2021-01-25 01:18

    Here's a slightly simpler version, though in the long term I'd recommend Ken's. In mine the rects are still just property bags, with no behavior on their own.

    var canvas = document.getElementById('canvas'),
        c = canvas.getContext('2d'),
        rects = [{x:0, y:15, w:5, h:5, vx:0, vy:1},
                 {x:50, y:5, w:15, h:15, vx:1, vy:0}];
    
    function move() {
        c.clearRect(0, 0, 500, 300);
    
        for (var i=0; i < rects.length; i++) {
            var rect = rects[i];
            c.fillRect(rect.x, rect.y, rect.w, rect.h),
            rect.x += rect.vx;
            rect.y += rect.vy;
        }
    }
    
    setInterval(move, 100);
    

提交回复
热议问题