d3.js 实现烟花鲜果
生活随笔
收集整理的這篇文章主要介紹了
d3.js 实现烟花鲜果
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今天在d3.js官網(wǎng)上看到了一個(gè)煙花的DEMO,是canvas制作的,于是我想用d3.js來(lái)實(shí)現(xiàn)它,js代碼只有幾行。好了廢話不多說(shuō),先上圖。
1 js 類
因?yàn)闊熁ㄒ邢侣涞男Ч?#xff0c;所以里面用到了一些簡(jiǎn)單的數(shù)學(xué)和物理知識(shí)來(lái)模擬重力,
class Firework {constructor() {this._heightLimit = [100,200];this._width = 1288;this._svg = null;this._tempObj = {};this._colors = d3.scaleLinear().domain([0,1,2,3,4,5]).range(['#f00','#ff0','#f0f','#0ff','#0f0'])this.initSvg();}initSvg() {this._svg = d3.select('body').append('svg');this._width = window.innerWidth;}randomPosition() {setInterval(() => {let x = Math.floor(Math.random() * (this._width - 200) + 100);let y = Math.floor(Math.random() * (this._heightLimit[1] - this._heightLimit[0]) + this._heightLimit[0]);let v = Math.random() * 20 + 40;let c = Math.random() * 4;this.renderFire(x,y,v,c)}, Math.floor(Math.exp(-Math.random()) * 800))}renderFire(x,y,v,c) {let stamp = new Date().getTime();let temp = d3.range(18).map(d => {return {cx: x + 1 * Math.sin(Math.PI * d / 9),cy: y - 1 * Math.cos(Math.PI * d / 9),vx: v * Math.sin(Math.PI * d / 9),vy: - v * Math.cos(Math.PI * d / 9)}})let t = 0;this._tempObj[stamp] = setInterval(() => {let cutStamp = new Date().getTime();for(var i=0; i<18; i++) {this._svg.append('circle').attr('cx', temp[i].cx + temp[i].vx * t / 8).attr('cy', t * t / 16 + temp[i].vy * t / 8 + temp[i].cy).attr('r', 6).attr('fill', this._colors(c)).attr('fill-opacity', 1).transition().duration(300).attr('fill-opacity', 0).on('end', function() {d3.select(this).remove();})}if(cutStamp - stamp > 2000){clearInterval(this._tempObj[stamp])}t ++;}, 40)}start() {this.randomPosition();} }2 css 代碼
* {padding: 0;margin: 0; } body {width: 100vw;height: 100vh;background: #000000; } .container {width: 100vw;height: 100vh;position: relative; } img {width: 100vw;height: 80vh; } svg {position: absolute;top: 0;left: 0;width: 100vw;height: 100vh; }3 html 代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>$Title$</title><link rel="stylesheet" type="text/css" href="css/base.css"/><script type="text/javascript" src="js/d3.v4.js"></script><script type="text/javascript" src="js/base.js"></script> </head> <body><div class="container"><img src="img/bg.jpg"></div> <script> var firework = new Firework(); firework.start() </script> </body> </html>是不是很簡(jiǎn)單
想預(yù)覽或者下載demo的人請(qǐng)移步至原文
原文地址 1
?
轉(zhuǎn)載于:https://www.cnblogs.com/vadim-web/p/11505868.html
總結(jié)
以上是生活随笔為你收集整理的d3.js 实现烟花鲜果的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: d3.js 制作简单的贪吃蛇
- 下一篇: 软件开发工具(第1章:绪论)