js实现canvas流体粒子模拟流动动画效果代码

代码语言:html

所属分类:粒子

代码描述:js实现canvas流体粒子模拟流动动画效果代码

代码标签: 流体 粒子 模拟 流动 动画 效果

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<html>
<head>
        <meta charset="UTF-8">
    <style>
        body {
            margin: 0;
            background: #000;
        }
        h1 {
            color: #ffffff;
            text-align: center;
            font-size: 20px;
        }
        canvas {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
            border: 2px solid white;
        }
    </style>

</head>
<body >
    <h1>单击并拖动!</h1>
    <canvas id="c" width="500" height="500"></canvas><script>
        /*
Comments were requested, here we go :)

Here's the rundown:

This script creates a grid of cells and a separate layer of particles that
float on top of the grid. Each cell of the grid holds X and Y velocity
(direction and magnitude) values and a pressure value.

Whenever the user holds down and moves their mouse over the canvas, the velocity
of the mouse is calculated and is used to influence the velocity and pressure in
each cell that was within the defined range of the mouse coordinates. Then, the
pressure change is communicated to all of the neighboring cells of those affected,
adjusting their velocity and pressure, and this is repeated over and over until
the change propogates to all of the cells in the path of the direction of movement.

The particles are randomly placed on the canvas and move according to the
velocity of the grid cells below, similar to grass seed floating on the surface
of water as it's moving. Whenever the particles move off the edge of the canvas,
they are "dropped" back on to the canvas in a random position. The velocity,
however, is "wrapped" around to the opposite edge of the canvas. The slowing
down of the movement is simulated viscosity, which is basically frictional drag
in the liquid.


Let's get started:
--------

This is a self-invoking function. Basically, that means that it runs itself
automatically. The reason for wrapping the script in this is to isolate the
majority of the variables that I define inside from the global scope and
only reveal specific functions and values. It looks like this:

(function(argument) {

    alert(argument);

})("Yo.");

and it does the same thing as this:

function thing(argument) {

    alert(argument);

}

thing("Yo.");

*/
        (function(w) {

            var canvas, ctx;

            /*
    This is an associative array to hold the status of the mouse cursor
    Whenever the mouse is moved or pressed, there are event handlers that
    update the values in this array.
    */
            var mouse = {
                x: 0,
                y: 0,
                px: 0,
                py: 0,
                down: false
            };

            /*
    These are the variable definitions for the values that will be used
    throughout the rest of the script.
    */
            var canvas_width = 500; //Needs to be a multiple of the resolution value below.
            var canvas_height = 500; //This too.

            var resolution = 10; //Width and height of each cell in the grid.

            var pen_size = 40; //Radius around the mouse cursor coordinates to reach when stirring

            var num_cols = canvas_width / resolution; //This value is the number of columns in the grid.
            var num_rows = canvas_height / resolution; //This is number of rows.
            var speck_count = 5000; //This determines how many particles will be made.

            var vec_cells = []; //The array that will contain the grid cells
            var particles = []; //The array that will contain the particles


            /*
    This is the main function. It is triggered to start the process of constructing the
    the grid and creating the particles, attaching event handlers, and starting the
    animation loop.
    */
            function init() {

                //These lines get the canvas DOM element and canvas context, respectively.
                canvas = document.getElementById("c");
                ctx = canvas.getContext("2d");

                //These two set the width and height of the canvas to the defined values.
                canvas.width = canvas_width;
                canvas.height = canvas_height;

                /*
        This loop begins at zero and counts up to the defined number of particles,
        less one, because array elements are numbered beginning at zero.
        */
                for (i = 0; i < speck_count; i++) {
                    /*
            This calls the function particle() with random X and Y values. It then
            takes the returned object and pushes it into the particles array at the
            end.
            */
                    particles.push(new particle(Math.random() * canvas_width, Math.random() * canvas_height));
                }

                //This loops through the count of columns.
                for (col = 0; col < num_cols; col++) {

                    //This defines the array element as another array.
                    vec_cells[col] = [];

                    //This loops through the count of rows.
                    for (row = 0; row < num_rows; row++) {

                        /*
                This line calls the cell() function, which creates an individual grid cell
                and returns it as an object. The X and Y values are multiplied by the
                resolution so that when the loops are referring to "column 2, row 2", the
                width and height of "column 1, row 1" are counted in so that the top-left
                corner of the new grid cell is at the bottom right of the other cell.
                */
                        var cell_data = new cell(col * resolution, row * resolution, resolution)

                        //This pushes the cell object into the grid array.
                        vec_cells[col][row] = cell_data;

                        /*
                These two lines set the object's column and row values so the object knows
                where in the grid it is positioned.
                */
                        vec_cells[col][row].col = col;
                        vec_cells[col][row].row = row;

                    }
                }


                /*
        These loops move through the rows and columns of the grid array again and set variables
        in each cell object that will hold the directional references to neighboring cells.
        For example, let's say the loop is currently on this cell:

        OOOOO
        OOOXO
        OOOOO
        These variables will hold the references to neighboring cells so you only need to
        use "up" to refer to the cell above the one you're currently on.
        */
                for (col = 0; col < num_cols; col++) {

                    for (row = 0; row < num_rows; row++) {

                        /*
                This variable holds the reference to the current cell in the grid. When you
                refer to an element in an array, it doesn't copy that value into the new
                variable; the variable stores a "link" or reference to that spot in the array.
                If the value in the array is changed, the value of this variable would change
                also, and vice-versa.
                */
                        var cell_data = vec_cells[col][row];

                        /*
                Each of these lines has a ternary expression. A ternary expression is similar
                to an if/then clause and is represented as an expression (e.g. row - 1 >= 0)
                which is evaluated to either true or false. If it's true, the first value after
                the question mark is used, and if it's false, the second value is used instead.

                If you're on the first row and you move to the row above, this wraps the row
                around to the last row. This is done so that momentum that is pushed to the edge
                of the canvas is "wrapped" to the opposite side.
                */
                        var row_up = (row - 1 >= 0) ? row - 1: num_rows - 1;
                        var col_left = (col - 1 >= 0) ? col - 1: num_cols - 1;
                        var col_right = (col + 1 < num_cols) ? col + 1: 0;

                        //Get the reference to the cell on the row above.
                        var up = vec_cells[col][row_up];
                        var left = vec_cells[col_left][row];
                        var up_left = vec_cells[col_left][row_up];
                        var up_right = vec_cells[col_right][row_up];

                        /*
                Set the current cell's "up", "left", "up_left" and "up_right" attributes to the
                respective neighboring cells.
                */
                        cell_data.up = up;
                        cell_data.left = left;
                        cell_data.up_left = up_left;
                        cell_data.up_right = up_right;

                        /*
                Set the neighbo.........完整代码请登录后点击上方下载按钮下载查看

网友评论0