Make and animate wave in canvas

后端 未结 3 688
夕颜
夕颜 2021-01-31 23:45

I’m looking for a way to create a wave in a shape designed in canvas. After much research I found something that is pretty close to what I want:

3条回答
  •  长情又很酷
    2021-02-01 00:14

    Since you are searching for a realistic effect, best idea might be to simulate the water. It is not that hard, in fact : water can be nicely enough approximated by a network of springs linked together.

    Result is quite good, you can find it here : http://jsfiddle.net/gamealchemist/Z7fs5/

    enter image description here

    So i assumed it was 2D effect and built an array holding, for each point of a water surface, its acceleration, speed, and position. I store them in a single array, at 3*i + 0, 3*i + 1, and 3*i+2.
    Then on each update, i simply apply newton's laws with elasticity, and with some friction to get the movement to stop.
    I influence each point so it goes to its stable state + get influenced by its right and left neighboor.
    (If you want smoother animation, use also i-2 and i+2 points, and lower kFactor.)

    var left = 0, y = -1;
    var right = water[2];
    for (pt = 0 ; pt < pointCount; pt++, i += 3) {
        y = right;
        right = (pt < pointCount - 1) ? water[i + 5] : 0;
        if (right === undefined) alert('nooo');
        // acceleration
        water[i] = (-0.3 * y + (left - y) + (right - y)) * kFactor - water[i + 1] * friction;
        // speed
        water[i + 1] += water[i] * dt;
        // height
        water[i + 2] += water[i + 1] * dt;
        left = y;
    }
    

    The draw is very simple : just iterate though the points and draw. But it's hard to get a smooth effect while drawing, since it's hard to have bezier and quadraticCurve to have their derivates match. I suggested a few drawing methods, you can switch if you want.

    Then i added rain, so that the water can move in a random way. Here it's just very simple trajectory, then i compute if there's collision with the water, and, if so, i add some velocity and shift the point.

提交回复
热议问题