<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
/* 画布位置 */
.box {
width: 500px;
height: 500px;
margin: 0 auto;
border: 1px solid #000;
}
</style>
<body>
<div class="box">
<canvas width="500" height="500" class="canvas" id="canvas"></canvas>
</div>
</body>
<script>
let canvas = document.getElementById("canvas")
// 绘制2d平面,没有3d
let ctx = canvas.getContext('2d')
let w = h = 500;
// 小球类
function Ball (){
/**
* x 坐标
* y 坐标
* r 半径
* color 颜色
* xa x轴速度
* ya y轴速度
* **/
this.x = Math.random() * (x-100) + 50 //x ∈ [50, 450)
this.y = Math.random() * (y-100) + 50 //y ∈ [50, 450)
this.r = Math.random() * 40 +10 //r ∈ [10, 50)
this.color = '#' + (Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')) //随机颜色
this.xa = Math.random() * 3 + 2 //[2,5) //随机激动速度,x轴
this.ya = Math.random() * 3 + 1 //[1, 4) //随机激动速度,y轴
}
// 绘制小球
Ball.prototype.show = function() {
// 碰撞检测
this.update()
// 绘制
yuan(ctx, this.x, this.y, this.r, 0, Math.PI * 2, true, this.color, this.color, "1px")
}
// 碰撞检测
Ball.prototype.update = function() {
// 如果x轴方向上,小球最左边或最右边超出画布,改变移动方向
if(this.x - this.r <=0 || this.x + this.r >=w) {
this.xa = -this.xa
}
// 更新x坐标
this.x += this.xa
// 如果y轴方向上,小球最上边或最下边超出画布,改变移动方向
if(this.y - this.r<=0 || this.y + this.r >=h) {
this.ya = -this.ya
}
// 更新y坐标
this.y += this.ya
}
// 创建一个小球的数组
var ball_array = []
for(let i = 0; i<=20;i++) {
let ball = new Ball()
ball_array.push(ball)
}
setInterval(function() {
// 清除画布,防止旧的小球和新的小球都出现在画布上
ctx.clearRect(0, 0, 500, 500)
for(let i = 0; i< ball_array.length;i++) {
let ball = ball_array[i]
ball.show()
}
}, 40)
function text(ctx, txt, x, y, fontsize,textAlign, textBaseline) {
ctx.font = `${fontsize}px 宋体`
ctx.textAlign = textAlign
ctx.textBaseline = textBaseline
ctx.fillStyle = "#000"
ctx.fillText(txt, x, y )
}
function yuan(ctx, x, y, r, start, end, xiang = true, linecolor, fillcolor, linewidth = "1px") {
// 作用就是拿起画笔
ctx.beginPath()
ctx.arc(x, y, r, start, end, xiang)
ctx.lineWidth = linewidth
// 填充颜色
ctx.fillStyle = fillcolor === undefined? "glob" : fillcolor;
ctx.fill()
ctx.strokeStyle = linecolor === undefined? "glob" : linecolor;
// 着色
ctx.stroke()
}
// 画线
function can(ctx, startx, starty, endx, endy, color, width) {
// 开始画一条路径
ctx.beginPath()
// 确定起始点
ctx.moveTo(startx, starty)
// 确定结束点
ctx.lineTo(endx, endy)
// 着色之前设置颜色和线宽
ctx.strokeStyle = color;
ctx.lineWidth = width
ctx.lineCap = "round"
// 着色
ctx.stroke()
// 关闭路径
ctx.closePath()
}
</script>
</html>
canvas实现动态小球
最新推荐文章于 2022-09-09 13:22:51 发布