|
|

楼主 |
发表于 2022-8-9 12:59
|
显示全部楼层
驱动多个对象运动的示例代码:
- <style>
- #papa { margin: auto; width: 1024px; height: 640px; box-shadow: 3px 3px 20px #000; position: relative; }
- #mama { position: absolute; width: 400px; height: 400px; left: calc(50% - 200px); top: calc(50% - 200px); border: 1px solid pink; }
- #canv { position: absolute; }
- </style>
- <div id="papa">
- <div id="mama"><canvas id="canv"></canvas></div>
- </div>
- <script>
- let width = canv.width = mama.offsetWidth, height = canv.height = mama.offsetHeight;
- let ctx = canv.getContext('2d');
- let ballAr = new Array(20);
- let num = (min, max) => {
- let number = Math.floor(Math.random() * (max-min+1)) + min;
- if(number == 0) number = 1;
- return number;
- }
- for(let j = 0; j < ballAr.length; j++) { //实例化对象
- let item = new Ball(
- num(20, width - 20), // x 坐标
- num(20, height - 20), // y 坐标
- num(5,10), // r 半径
- 0.5 * num(-2, 2), // vx 偏移量
- 0.5 * num(-2,2), // vy 偏移量
- `rgba(${num(0,255)}, ${num(0,255)}, ${num(0,255)}, 075)` //color 颜色
- );
- ballAr[j] = item;
- }
- //绘制对象
- function Ball(x, y, r, vx, vy, color) {
- this.x = x;
- this.y = y;
- this.r = r;
- this.vx = vx;
- this.vy = vy;
- this.color = color;
- }
- //绘制函数 :画圆
- Ball.prototype.draw = function() {
- ctx.beginPath();
- ctx.fillStyle = this.color
- ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
- ctx.fill();
- }
- //移动函数 :变换圆心
- Ball.prototype.move = function() {
- if (this.x + this.r >= width || this.x - this.r <= 0) this.vx = -this.vx;
- if (this.y + this.r >= height || this.y - this.r <= 0) this.vy = -this.vy;
- this.x += this.vx;
- this.y += this.vy;
- }
- //渲染函数 :整合绘制、更新函数+递归调用
- function render() {
- ctx.clearRect(0,0,width,height);
- ctx.fillStyle = 'transparent';
- ctx.fillRect(0,0,width,height);
- for(item of ballAr) {
- item.draw();
- item.move();
- }
- requestAnimationFrame(render);
- }
- render();
- </script>
复制代码
|
评分
-
| 参与人数 2 | 威望 +60 |
金钱 +120 |
经验 +60 |
收起
理由
|
上海朝阳
| + 30 |
+ 60 |
+ 30 |
神 |
加林森
| + 30 |
+ 60 |
+ 30 |
很给力! |
查看全部评分
|