携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第29天,点击查看活动详情
效果图如下
总代码
<!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>
<style>
canvas{
margin: 0 auto;
border: 1px solid #000;
display: block;
}
</style>
</head>
<body>
<canvas id="cont" width="500px" height="500px">你好呀</canvas>
<script>
// 使用原生js操作canvas
// 1.获取画布
var canvas = document.querySelector('#cont')
// 2.获取画布的上下文
var ctx = canvas.getContext('2d')
// 创建小球
// 2.获取窗口可视区域宽高
// var w = document.documentElement.clientWidth-6
// var h = document.documentElement.clientHeight-6
var w =h = 500
// // 3.更新canvas宽高
// canvas.width = w
// canvas.height = h
// 产生随机数
function r(num) {
return parseInt(Math.random()*num)
}
// 1.创建小球类
function Ball(text) {
this.x = r(380)+60 // 60,440
this.y = r(380)+60
this.r = r(30)+10 // [10,60)
// 随机颜色
this.color = '#'+parseInt(Math.random()*0xffffff).toString(16)
this.xSpeed = r(3)+2 // 2,5
this.ySpeed = r(3)+1 // 1,4
//接收外部 参数
this.text =text
}
// 2.定义小球显示方法
Ball.prototype.show = function () {
this.run() // 更新坐标
drawCircle(this.x,this.y,this.r,this.color) //画小球
drawText(this.text,this.x+this.r,this.y) //画文字
}
//定义小球运动的方法(碰撞检测)
Ball.prototype.run = function () {
if (this.x-this.r<=0 || this.x+this.r>=w) {
this.xSpeed = -this.xSpeed
}
this.x = this.x+this.xSpeed
if (this.y-this.r<=0 || this.y+this.r>=h) {
this.ySpeed = -this.ySpeed
}
this.y = this.y+this.ySpeed
}
var titleArr = 'JavaScrip HTML5前端 JAVA PHP jQuery Canvas CSS CSS3 全栈工程师 Vue.js React'.split(' ')
// 存放小球
var ballArr = []
for (var i = 0; i < 5; i++) {
//当前小球
var ball = new Ball(titleArr[i]) // 传入title
ballArr.push(ball)
ball.show()
// 小球连线 a球 和b球
for (var j = 0; j < i; j++) {
//取出当前小球前面的小球
var prevBall = ballArr[j]
drawLine(ball.x,ball.y,prevBall.x,prevBall.y)
}
}
//5.小球运动
setInterval(() => {
// 清除画布
ctx.clearRect(0,0,w,h)
for (var i = 0; i < ballArr.length; i++) {
var ball = ballArr[i]
ball.show()
// 小球连线 a球 和b球
for (var j = 0; j < i; j++) {
//取出当前小球前面的小球
var prevBall = ballArr[j]
drawLine(ball.x,ball.y,prevBall.x,prevBall.y)
}
}
}, 10);
// 画直线
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 drawText(text,x,y) {
ctx.font = '20px 微软雅黑'
ctx.textAlign = 'top'
ctx.textBaseline = 'middle'
ctx.fillText(text,x,y)
}
// 画圆
function drawCircle(x,y,r,color){
ctx.beginPath()
ctx.arc(x,y,r,0,Math.PI*2)
ctx.fillStyle= color || '#000'
ctx.fill()
}
</script>
</body>
</html>