随机方块 、 构造 渲染 随机 实现功能,this 和在那里调用函数很重要
2018-05-04 11:25
363 查看
//div 的id为 map var Tools = { getRandom: function (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }; // 构造函数 渲染函数 function Box(parente, options) { //构造函数是 options(作为一个对象)为各种属性的集合 parent为渲染的地址 options = options || {}; this.width = options.width || 20; this.height = options.height || 20; //让这个对象的高度 等于传过来的参数的高度 下面可以设置 this.x = options.x || 0; this.y = options.y || 0; this.backgroundColorcolor = options.backgroundColor || 'red'; this.div = document.createElement('div'); //this指向的是调用构造函数的那个对象 parente.appendChild(this.div); //parent就是在哪里创建的div 是div的父元素 this.parente = parente; //为下面 random 获取盒子的宽度 //因为构造函数中的变量 是局部变量,若下面的渲染要使用这个变量 可以吧这个变量通过this变成一个属性 this.render(); } Box.prototype.render = function () { var div = this.div; // 为下面的 设置样式 写的方便 div.style.width = this.width + 'px'; div.style.height = this.height + 'px'; div.style.left= this.x + 'px'; div.style.top = this.y + 'px'; div.style.backgroundColor = this.backgroundColorcolor; div.style.position = 'absolute'; } Box.prototype.random = function () { var x = Tools.getRandom(0, this.parente.offsetWidth / this.width - 1) * this.width; //this.parent 上面的parent为了让这里获取到 而改变成this.parent var y = Tools.getRandom(0, this.parente.offsetHeight / this.height - 1) * this.height; this.div.style.left = x + 'px'; this.div.style.top = y + 'px'; } //实现功能 这里是在其他地方测试代码的集合 var map = document.getElementById('map'); var arry = []; // 把下面创建好的div 放到一个数组里 为了下面定时器做准备 在理解??? for (var i = 0; i < 10; i++) { var r = Tools.getRandom(0, 255); var g = Tools.getRandom(0, 255); var b = Tools.getRandom(0, 255); //box就是 通过new Box 创建的一个对象 在for循环里 创建了 十个box 参数的意思就是 在那里创建 和随机生成的颜色 //因为 在这里生成十个box 所以 在这里去渲染十个的颜色 backgroundColor作为options的一个属性 其他的宽高位置等都是默认值 var box = new Box(map, { //用对象的方式传参 // backgroundColor: 'rgb('+ r +','+ g +','+ b +')' backgroundColor: 'rgb('+ r +','+ g +','+ b +')' // backgroundColor: 'rgb('+ r +','+ g +','+ b +')' }); arry.push(box); } setInterval(function () { for (var i = 0; i < arry.length; i++) { var box = arry[i]; box.random(); //这里调用 构造函数创建的对象里的 random方法 随机位置 } }, 600)阅读更多
相关文章推荐
- 利用MySQL自带的C API函数实现数据库功能调用
- linux 调用系统函数来实现 ATM 自动取款机功能 (进程间通信)
- linux 调用系统函数来实现 ATM 自动取款机功能 (进程间通信)
- C++学习 【4.2】 利用函数实现指定的功能---函数的调用
- 1#include<stdio.h> #include<string.h> int deng(char a[],ch、用函数实现登陆功能(三次机会),然后在主函数中根据调用后的结果判断 登陆成功与否。
- 模拟实现printf函数,可完成下面的功能 能完成下面函数的调用。 print("s ccc d.\n","hello",'b','i','t',100); 函数原型: print(char *
- Qt实现截图选择框(仅实现选择框创建,非完整的截图功能)并发射信号给调用的槽函数
- 内存管理以及相关函数(系统调用和内核函数功能和实现)资料(汇总)
- 编写函数实现随机产生指定范围的整数的功能
- UNIX环境高级编程学习笔记(四)不调用fcntl函数实现dup2的功能
- 习题3.2:不调用fcntl函数来实现dup2的功能
- 构造自己的动画函数:animation,stop功能的实现
- Android 系统调用实现函数功能--SVC指令的实现与检测
- 函数走步功能的实现 即随机步法的初步实现
- 小字典之MFC简单的多线程调用类的成员函数实现逐步画线功能 VS2015 C++ 完成
- 不调用fcntl,自己实现dup2函数功能
- 用DOS功能调用实现简单输入输出(汇编)
- Java中异或运算实现两个整数的交换以及其功能函数实现
- C#+arcengine调用GP工具实现产生随机点的功能
- JavaScript实现显示函数调用堆栈的方法