本篇文章给大家带来的内容是关于用canvas实现简单的下雪效果(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
首先新建一个html文件,将body的背景设置为天空的那种深蓝色,并创建一个canvas,canvas的操作逻辑都放在snow.js中:
76c82f278ac045591c9159d381de2c57 93f0f5c25f18dab9d176bd4f6de5d30e c9ccee2e6ea535a969eb3f532ad9fe89 body { background-color: #102a54; } 531ac245ce3e4fe3d50054a55f265927 9c3bca370b5104690d9ef395f2c5f8d1 6c04bd5ca3fcae76e30b72ad730ca86d c9ecf200f89536d0c4e2649515b07fa8c2caaf3fc160dd2513ce82f021917f8b ac9770e460dedf7fd642b68ac6153a3f2cacc6d41bbb37262a98f745aa00fbf0 36cc49f0c466276486e50c850b7e4956 73a6ac4ed44ffec12cee46588e518a5e
canvas的操作将在页面加载完之后执行,首先获取到canvas的二维context,并将canvas宽高设置为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; }
天空背景完成后,我们来创建雪花,思路比较简单,我们让屏幕上保持一个额定数量的雪花,并给每个雪花一个随机的位置、随机的大小以及随机的下落速度:
... var flakesCount = 100; // 雪花个数 var flakes = []; for (var i = 0; i 60308be2d3db46a4196a16f2fc374059 H) { flakes[i] = { x: Math.random() * W, y: 0, r: flake.r, d: flake.d }; } } } setInterval(drawFlakes, 25);
完成,我们来看一下实际效果:
嗯,还挺像那么回事儿:)
完整代码:
<!DOCTYPE html> <head> <style> body { background-color: #102a54; } </style> </head> <body> <canvas id='sky'></canvas> <script src="snow.js"></script> </body> </html>
window.onload = function () { // get the canvas and context var canvas = document.getElementById('sky'); var ctx = canvas.getContext('2d'); // set canvas dims to window height and width var W = window.innerWidth; var H = window.innerHeight; canvas.width = W; canvas.height = H; // generate snowflakes and apply attributes var flakesCount = 100; var flakes = []; // flake instances // loop through the empty flakes and apply attributes for (var i = 0; i < flakesCount; i++) { flakes.push({ x: Math.random() * W, y: Math.random() * H, r: Math.random() * 5 + 2, // 2px - 7px d: Math.random() + 1 }); } // draw flakes onto canvas function drawFlakes() { ctx.clearRect(0, 0, W, H); ctx.fillStyle = '#fff'; ctx.beginPath(); for (var i = 0; i < flakesCount; i++) { var flake = flakes[i]; ctx.moveTo(flake.x, flake.y); ctx.arc(flake.x, flake.y, flake.r, 0, Math.PI * 2, true); } ctx.fill(); moveFlakes(); } var angle = 0; function moveFlakes() { angle += 0.01; for (var i = 0; i < flakesCount; i++) { var flake = flakes[i]; flake.y += Math.pow(flake.d, 2) + 1; flake.x += Math.sin(angle) * 2; if (flake.y > H) { flakes[i] = { x: Math.random() * W, y: 0, r: flake.r, d: flake.d }; } } } setInterval(drawFlakes, 25); }
以上是用canvas实现简单的下雪效果(附代码)的详细内容。更多信息请关注PHP中文网其他相关文章!