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 neighboring cell's opposite attributes to point to the current cell. */ up.down = vec_cells[col][row]; left.right = vec_cells[col][row]; up_left.down_right = vec_cells[col][row]; up_right.down_left = vec_cells[col][row]; } } /* These lines create triggers that fire when certain events happen. For instance, when you move your mouse, the mouse_move_handler() function will run and will be passed the event object reference into it's "e" variable. Something to note, the mousemove event doesn't necessarily fire for *every* mouse coordinate position; the mouse movement is sampled at a certain rate, meaning that it's checked periodically, and if the mouse has moved, the event is fired and the current coordinates are sent. That's why you'll see large jumps from one pair of coordinates to the next if you move your mouse very fast across the screen. That's also how I measure the mouse's velocity. */ w.addEventListener("mousedown", mouse_down_handler); w.addEventListener("touchstart", mouse_down_handler); w.addEventListener("mouseup", mouse_up_handler); w.addEventListener("touchend", touch_end_handler); canvas.addEventListener("mousemove", mouse_move_handler); canvas.addEventListener("touchmove", touch_move_handler); //When the page is finished loading, run the draw() function. w.onload = draw; } /* This function updates the position of the particles according to the velocity of the cells underneath, and also draws them to the canvas. */ function update_particle() { //Loops through all of the particles in the array for (i = 0; i < particles.length; i++) { //Sets this variable to the current particle so we can refer to the particle easier. var p = particles[i]; //If the particle's X and Y coordinates are within the bounds of the canvas... if (p.x >= 0 && p.x < canvas_width && p.y >= 0 && p.y < canvas_height) { /* These lines divide the X and Y values by the size of each cell. This number is then parsed to a whole number to determine which grid cell the particle is above. */ var col = parseInt(p.x / resolution); var row = parseInt(p.y / resolution); //Same as above, store reference to cell var cell_data = vec_cells[col][row]; /* These values are percentages. They represent the percentage of the distance across the cell (for each axis) that the particle is positioned. To give an example, if the particle is directly in the center of the cell, these values would both be "0.5" The modulus operator (%) is used to get the remainder from dividing the particle's coordinates by the resolution value. This number can only be smaller than the resolution, so we divide it by the resolution to get the percentage. */ var ax = (p.x % resolution) / resolution; var ay = (p.y % resolution) / resolution; /* These lines subtract the decimal from 1 to reverse it (e.g. 100% - 75% = 25%), multiply that value by the cell's velocity, and then by 0.05 to greatly reduce the overall change in velocity per frame (this slows down the movement). Then they add that value to the particle's velocity in each axis. This is done so that the change in velocity is incrementally made as the particle reaches the end of it's path across the cell. */ p.xv += (1 - ax) * cell_data.xv * 0.05; p.yv += (1 - ay) * cell_data.yv * 0.05; /* These next four lines are are pretty much the same, except the neighboring cell's velocities are being used to affect the particle's mov.........完整代码请登录后点击上方下载按钮下载查看
网友评论0