1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 现绚丽的小球(js面向对象)

现绚丽的小球(js面向对象)

时间:2021-04-09 06:10:17

相关推荐

现绚丽的小球(js面向对象)

index.html

<!DOCTYPE html><html><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>五彩特效</title><style>* {margin: 0;padding: 0;list-style: none;}html,body,div {width: 100%;height: 100%;}#box {position: relative;background: #000;}</style></head><body><div id="box"></div></body><script src="js/ball.js"></script><!-- <script>var ball = new Ball({parentId: 'box',left: 100,top: 200,bgColor: 'yellow'})ball.render()</script> --><script>// min and max includedfunction randomIntFromInterval(min, max) {return Math.floor(Math.random() * (max - min + 1) + min);}// 1. 获取当前盒子的nodevar box = document.getElementById('box');// 数组的颜色var colorArr = ['red', 'white', 'green', 'pink', 'blue', 'red', 'yellow', 'purple'];// 存放创建小球var ballArr = [];// 2. 监听鼠标在盒子上的移动box.onmousemove = function(ev) {// console.info(ev)// 创建小球var ball = new Ball({parentId: 'box',left: ev.clientX, // 当前鼠标X坐标top: ev.clientY, // 当前鼠标Y坐标bgColor: colorArr[randomIntFromInterval(0, colorArr.length - 1)] // 颜色随机});ballArr.push(ball) // 将每次创建出来的小球存起一个数组};// 3. 设置定时器setInterval(() => {// 3.1 清除上一针的小球for (var i = 0; i < box.children.length; i++) {box.children[i].remove()}// 3.2 让小球移动 变小for (var j = 0; j < ballArr.length; j++) {ballArr[j].render()ballArr[j].update()}}, 50);</script></html>

ball.js

function Ball(options) {this._init(options)}Ball.prototype = {// 初始化_init: function(options) {// 圆的必要属性this.parentId = options.parentId;this.left = options.left;this.top = options.top;this.r = 60;this.bgColor = options.bgColor || 'red'// 小球的变化量this.dX = randomIntFromInterval(-5, 5); // 水平this.dY = randomIntFromInterval(-5, 5); // 垂直this.dR = randomIntFromInterval(1, 3); // 圆的半径},// 渲染render: function() {var parentNode = document.getElementById(this.parentId);var childNode = document.createElement('div');parentNode.appendChild(childNode)childNode.style.position = 'absolute';childNode.style.left = this.left + 'px';childNode.style.top = this.top + 'px';childNode.style.width = this.r + 'px';childNode.style.height = this.r + 'px';childNode.style.borderRadius = '50%';childNode.style.backgroundColor = this.bgColor;},// 更新update: function() {this.left += this.dX;this.top += this.dY;this.r -= this.dR;// 圆的半径小0的时候 干掉小球if (this.r <= 0) {this.r = 0;// 过滤r=0的小球ballArr = ballArr.filter(item => item.r != 0);}}};

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。