<!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>
<body>
<canvas id="can" width="500px" height="500px" style="border: 1px solid #999;"></canvas>
<script>
var c = document.querySelector("#can");
var ctx = c.getContext('2d');
var w = 500;
var h = 500
// 画圆
function drawCircle(x, y, r, color) {
ctx.beginPath();
ctx.fillStyle = color || '#000';
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fill();
}
// 画文字
function drawText(text, x, y) {
ctx.font = "20px 微软雅黑";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(text, x, y)
}
// 画直线
function drawLine(x1, y1, x2, y2, color) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = color || "#000";
ctx.stroke();
ctx.closePath();
}
// 创建随机数据
function r(num) {
return Math.random() * num
}
// 1.创建小球
function Ball(text) {
this.x = r(380) + 60; // [60,440]
this.y = r(380) + 60 //[60,440]
this.r = r(30) + 10; //[10,40)
this.color = '#' + parseInt(Math.random() * 0xffffff).toString(16); // 随机颜色
this.xSpeed = r(1) + 2; //[2,3] 随机x轴速度
this.ySpeed = r(1) + 1; // [1,2] 随机y轴速度
this.text = text; //接收文字
}
// 2.定义小球显示方法
Ball.prototype.show = function () {
// 显示球
drawCircle(this.x, this.y, this.r, this.color)
// 显示文字
drawText(this.text, this.x+this.r, this.y)
this.run(); // 创建小球之后就执行运动的方法
}
// 3.定义小球运动的方法--碰撞检测
Ball.prototype.run = function () {
// 初始位置减半径小于0 说明超出左边的边框
// 初始位置加上半径大于设置的宽度,说明超出了右边的宽度
if (this.x - this.r <= 0 || this.x + this.r > w) {
this.xSpeed = -this.xSpeed;
}
// y轴也是一样的
if (this.y - this.r <= 0 || this.y + this.r > w) {
this.ySpeed = -this.ySpeed;
}
// 改变位置
this.x = this.x + this.xSpeed
this.y = this.y + this.ySpeed
}
// 3.创建一个小球的数组
// 5. 分割成数组
var titleArr = 'js html java php jq canvas css css3 angular bootstrap node mysql vue react'.split(' ')
var barrArr = []; // 存放小球的数组
for (let i = 0; i < 5; i++) {
// 当前小球
var ball = new Ball(titleArr[i]); // 传入文字
// 放入小球数组 以便于单个使用,设置运动
barrArr.push(ball);
ball.show();
// 小球连线 当前小球和前面的小球相连 这里只能画一次所以再setInterval里再写一次
for (let j = 0; j < i; j++) {
// 取出当前小球前面的小球
var prevBall = barrArr[j];
// 当前小球的x 和 y 前面小球的x 和 前面小球的y
drawLine(ball.x,ball.y,prevBall.x,prevBall.y,this.color);
}
}
// 4.小球运动
setInterval(function () {
ctx.clearRect(0, 0, w, h);
for (let i = 0; i < barrArr.length; i++) {
var ball = barrArr[i];
// ball.run();
ball.show();
// 小球连线 当前小球和前面的小球相连
for (let j = 0; j < i; j++) {
// 取出当前小球前面的小球
var prevBall = barrArr[j];
// 当前小球的x 和 y 前面小球的x 和 前面小球的y
drawLine(ball.x,ball.y,prevBall.x,prevBall.y,ball.color);
}
}
}, 10)
</script>
</body>
</html>
canvas线性小球
最新推荐文章于 2022-03-23 14:32:13 发布