[面向对象的案例]在canvas画布内实现小球的随机移动
来源:互联网 发布:淘宝企业店铺过户 编辑:程序博客网 时间:2024/06/05 05:33
[面向对象的案例]在canvas画布内实现小球的随机移动
//css部分,给画布设置边框<style> canvas { border:1px solid orange; }</style>//html 添加画布<canvas id="game" width="500" height="500"></canvas>
准备工作
先确定所需要的属性
小球的起始xy坐标、R半径、颜色、速度speedXY。
//创建球构造函数 function ball() { this.r = this.rand(20); this.x = this.r; this.y = this.r; this.speedX = this.rand(10); this.speedY = this.rand(10); this.width = 0; this.height = 0; this.canvas = {}; this.color = 'rgb('+this.rand(255)+','+this.rand(255)+','+this.rand(255)+')'; this.init(); }//2.向原型链添加方法ball.prototype = { init:function () { var game = document.getElementById('game'); this.canvas = game.getContext('2d'); this.width=game.width; this.height=game.height; }, rand:function (num) { return Math.floor(Math.random() * num+1); }, play:function () { this.x += this.speedX; this.y += this.speedY; if (this.x>this.width-this.r) { this.speedX = -this.speedX; } if (this.x<this.r) { this.speedX = Math.abs(this.speedX); } if (this.y>this.width-this.r) { this.speedY = -this.speedY; } if (this.y<this.r) { this.speedY = Math.abs(this.speedY); } this.canvas.beginPath(); this.canvas.fillStyle = this.color; this.canvas.arc(this.x, this.y, this.r, 0, 2 * Math.PI); this.canvas.fill(); } }; //3.创建100个小球 var arr = []; for (var i=0;i<100;i++) { arr[i] = new ball(); } //4.使用定时器,每个30ms刷新屏幕 setInterval(function () { arr[0].canvas.clearRect(0,0,500,500); for (var i=0;i<arr.length;i++) { arr[i].play(); } },30)
阅读全文
0 0
- [面向对象的案例]在canvas画布内实现小球的随机移动
- Canvas画板实现一个简单的球在盒子内随机移动效果
- EasyX实现小球的移动
- canvas绑定事件的时候 获得鼠标点击的地方在canvas画布内的坐标的方法
- android中自定义画布Canvas的实现
- html5中canvas画布实现手机端和移动端的刮刮乐效果
- Canvas(画布)的使用
- Canvas 画布的属性
- canvas画布的用法
- h5的画布Canvas
- canvas画布的使用
- Canvas绘制小球(面向对象思想)
- java实现随机动态的小球
- 10款面向HTML5 画布(Canvas)的JavaScript库
- 10款面向HTML5 画布(Canvas)的JavaScript库
- canvas躁动的小球
- 在画布范围内移动的圆点
- 小球在屏幕上随机移动
- OkHttpClient GET与POST请求
- Docker--docker使用及自定义Dockerfile构建镜像
- isNaN在JS中的坑
- 关于Ubuntu中Could not get lock /var/lib/dpkg/lock解决方案
- 语言比较
- [面向对象的案例]在canvas画布内实现小球的随机移动
- vim 常用快捷键
- Java Synchronized 和 Static 关键字的总结与使用
- 2017hdu新生赛 1001考研
- FFmpeg之AVStream
- 【回顾】从零开始入门机器学习算法实践
- 识别物体的滑窗是怎么快速建立的?
- 用GPU加速深度学习: Windows安装CUDA+TensorFlow教程
- 快速排序&冒泡排序