Simply canvas animation

前端 未结 2 1247
北恋
北恋 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);
    
    0 讨论(0)
  • 2021-01-25 01:25

    You can certainly turn them into objects, for example:

    function Rect(x, y, w, h, dltX, dltY, color) {
    
        var me = this;
    
        this.x = x;
        this.y = y;
        this.width = w;
        this.height = h;
    
        this.deltaX = dltX || 0;       /// and deltas can be optional
        this.deltaY = dltY || 0;
        this.color = color || '#000';  /// color is optional
        
        this.update = function(ctx) {
            me.x += me.deltaX;
            me.y += me.deltaY;
            
            ctx.fillStyle = me.color;
            ctx.fillRect(me.x, me.y, me.width, me.height);
        }    
    }
    

    The deltaX and deltaY are how much you want to move the rectangle for each update. If you set these to for example 1 then x and y will be increased with 1 each time update() is called.

    Using deltas makes it easy to create bounces (see demo below) by simply reversing the delta value (ie. delta = -delta) as well as things such as acceleration, variate speed, you can feed them through trigonometric functions to have the object move in a specific angle and so forth.

    You can used fixed values if you desire but you will discover that deltas are beneficial in the long run (ref. comment: it's actually a very classic method used in for instance the first Pong games :-) ).

    Online demo here

    Now that we have defined the object we can simply create instances of it and store them in an array:

    var rects = [
        new Rect(10, 10, 100, 100, 1, -2),
        new Rect(100, 1, 50, 50, 2, 1, '#f00'),
        ...
    ]
    

    From here it's simply a matter of iterating the array to update each object:

    function move() {
        ctx.clearRect(0, 0, width, height);
    
        for(var i = 0, r; r = rects[i]; i++) {
            /// check any conditions here
            r.update(ctx);
        }
        requestAnimationFrame(move);
    }
    
    requestAnimationFrame(move); /// start loop
    
    0 讨论(0)
提交回复
热议问题