html 代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>canvas</title>
- </head>
- <body>
- <canvas width="1000" height="700" id="pad" style="border: 1px solid black;background: black"></canvas>
- </body>
- <script>
- // 需求: 1. 鼠标移入画布时自动画小球
- // 2. 所画的小球随机填充颜色
- // 3. 小球做自由落体运动
- // 4. 运动到底部有回落 (模拟一个球落地的状态)
- // 步骤: 1 创建画布并确定画布的环境时 2d 的
- var pad = document.getElementById('pad');
- var ctx = pad.getContext('2d');
- //2. 用面向对象的方法来绘制小球
- var ballList = [];// 用来放画好的小球
- function Ball(x,y,r,vx,vy,col) {
- //x,y 小球圆心位置
- this.x = x;
- this.y = y;
- this.r = r;// 半径
- this.vx = vx;
- this.vy = vy;
- this.gravity = 0.5;// 重力加速度
- this.col = col;
- this.drawBall = function () {
- ctx.beginPath();
- ctx.fillStyle = col;
- ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, true);
- ctx.fill()
- };
- this.move = function () {
- ctx.fill();
- this.x = this.x + this.vx;
- this.y = this.y + this.vy;
- this.vy = this.vy + this.gravity;
- if(this.y> pad.height - this.r){// 到边界时改变运动方向
- this.vy = this.vy*-0.9;
- this.vx = this.vx*0.9
- }
- if(Math.abs(this.vy) <0.2 && this.y>pad.height-this.r){//y 方向的运动范围控制
- this.gravity = 0;
- this.vy = 0;
- }
- if(this.x>pad.width-this.r || this.x <this.r){//x 方向的边界处理 (相当于碰撞检测)
- this.vx =this.vx*-1
- }
- if(this.vy==0){
- this.vx = this.vx*0.98;
- }
- }
- }
- var newBall;
- pad.timer = null;
- pad.onmousedown = function (ev) {
- clearInterval(this.timer);
- this.timer = setInterval(function () {
- var num = Math.floor(Math.random()*225),
- num1 = Math.floor(Math.random()*225),
- num2 = Math.floor(Math.random()*225);// 随机生成 0-225 的数
- var str = 'rgba('+ num +','+ num1+','+ num2 +',0.8)';// 颜色随机 (此处的三个数是三个不同的变量)
- var r = Math.random()*50+1;// 半价随机
- var vx = Math.random()*10-5;//
- newBall = new Ball(ev.clientX,ev.clientY,r,vx,0,str);
- newBall.drawBall();
- ballList.push(newBall);
- },20);
- document.onmouseup = function () {
- clearInterval(pad.timer);
- }
- };
- setInterval(function () {
- ctx.clearRect(0,0,pad.width,pad.height);// 清空当前的画布
- for (var i = 0; i < ballList.length; i++) {
- var obj = ballList[i];
- obj.drawBall();
- obj.move()
- }
- },10)
- </script>
- </html>
鼠标按下时画布上会随机生成小球, 按照理解小球应该会产生堆积, 但是不知道该怎么实现, 哪位大侠肯指点一二, 定不胜感激
来源: http://www.qdfuns.com/article/31702/a790b31f96acf27a413bf90261ccbb85.html