The content of this article is about using canvas to achieve a simple snowing effect (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
First create a new html file, set the background of the body to the dark blue of the sky, and create a canvas. The operation logic of the canvas is placed in snow.js:
nbsp;html>
canvas The operation will be executed after the page is loaded. First, the two-dimensional context of the canvas is obtained, and the width and height of the canvas are set to the width and height of the window to ensure that the sky background covers the entire window. snow.js
:
window.onload = function () { var canvas = document.getElementById('sky'); var ctx = canvas.getContext('2d'); var W = window.innerWidth; var H = window.innerHeight; canvas.width = W; canvas.height = H; }
After the sky background is completed, we create snowflakes. The idea is relatively simple. We keep a rated number of snowflakes on the screen and give each snowflake a random Position, random size and random falling speed:
... var flakesCount = 100; // 雪花个数 var flakes = []; for (var i = 0; iNext we need to draw these 100 snowflakes. For simplicity, we use small white circles to represent snowflakes:
function drawFlakes() { ctx.clearRect(0, 0, W, H); ctx.fillStyle = '#fff'; ctx.beginPath(); for (var i = 0; iAfter the snowflakes are drawn, we need to make the snowflakes move and have a falling effect. Our idea is to set a timer and re-render the canvas every 25ms. Each time the snowflake is rendered, it moves downward for a certain distance. The higher the density of the snowflake, the faster it falls. And use the
Math.sin
function to create the effect of snowflakes fluttering left and right. When the snowflakes fall outside the window, the snowflakes are moved to the top of the window and fall again. The implementation is as follows:var angle = 0; function moveFlakes() { angle += 0.01; for (var i = 0; i H) { flakes[i] = { x: Math.random() * W, y: 0, r: flake.r, d: flake.d }; } } } setInterval(drawFlakes, 25);Copy after login
Complete, we Let’s take a look at the actual effect:
Well, it looks like that:)
Full code:
rrreeThe above is the detailed content of Use canvas to achieve a simple snowing effect (with code). For more information, please follow other related articles on the PHP Chinese website!