大多数人一到冬天就十分期待下雪,且认为下雪是十分浪漫的事情。网络上说程序员不懂得浪漫其实是不对的,程序员们可以使用计算机语言制造浪漫,例如使用Javascript制作下雪特效。
1、效果实现功能:
(1)最多片数;
(2)雪花形状;
(3)坠落速度;
2、实现原理:
将代码保存为 js 文件,最后在网站引用即可。
第一步:控制下雪可配置属性(片数、形状和坠落速度)
function snowFall(snow) { snow = snow || {}; this.maxFlake = snow.maxFlake || 200; this.flakeSize = snow.flakeSize || 10; this.fallSpeed = snow.fallSpeed || 1; }
第二步:创建画布,定义雪花形状
function createFlakes() { var maxFlake = this.maxFlake, flakes = this.flakes = [], canvas = this.canvas; for (var i = 0; i < maxFlake; i++) { flakes.push(new flakeMove(canvas.width, canvas.height, this.flakeSize, this.fallSpeed)) } }
第三步:设置雪运动对象
function flakeMove(canvasWidth, canvasHeight, flakeSize, fallSpeed) { this.x = Math.floor(Math.random() * canvasWidth); this.y = Math.floor(Math.random() * canvasHeight); this.size = Math.random() * flakeSize + 2; this.maxSize = flakeSize; this.speed = Math.random() * 1 + fallSpeed; this.fallSpeed = fallSpeed; this.velY = this.speed; this.velX = 0; this.stepSize = Math.random() / 30; this.step = 0 }
第四步:清空雪花
function drawSnow() { var maxFlake = this.maxFlake, flakes = this.flakes; ctx = this.ctx, canvas = this.canvas, that = this; ctx.clearRect(0, 0, canvas.width, canvas.height); for (var e = 0; e < maxFlake; e++) { flakes[e].update(); flakes[e].render(ctx); } this.loop = requestAnimationframe(function() { drawSnow.apply(that); }); }
以上就是Javascript中下雪特效的代码过程,小伙伴们可以更改设置的数据改变特效的效果哦~更多js教程:js教程。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)