<!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>
div{
height: 800px;
width: 800px;
margin: 0 auto;
}
canvas{
border: 1px solid red;
position: relative;
left: 50%;
transform: translate(-50%);
top: 10%;
}
</style>
</head>
<body>
<div class="canvas" style="background-color:pink">
<canvas height="500" id="mycanvas" width="500"></canvas>
</div>
</body>
</html>
<script>
var c = document.getElementById("mycanvas");
var ctx = c.getContext("2d");
let h = w = 500
var arr = ["css","js","javascript","html","react","vue"]
// 随机颜色
var getRandomColor = function(){
return (function(m,s,c){
return (c ? arguments.callee(m,s,c-1) : '#') +
s[m.floor(m.random() * 16)]
})(Math,'0123456789abcdef',5)
}
function Ball(x,y,r,color,width,xSpeed,ySpeed,text){
this.x = x
this.y = y
this.r = r
this.color = getRandomColor()
this.width = width
this.xSpeed = xSpeed ? xSpeed : 3
this.ySpeed = ySpeed ? ySpeed : 4
this.text = text
}
function getCircle(x,y,r,color){
ctx.beginPath()
ctx.arc(x , y , r ,Math.PI*2 , false)
ctx.fillStyle = color
ctx.fill()
ctx.closePath()
}
// 绘制 文字
function getText(text , x ,y , color){
ctx.font = "16px 微软雅黑";
ctx.fillText(text,x ,y)
ctx.fillStyle = color
}
// 实心 小球
Ball.prototype.render = function(){
getCircle(this.x , this.y , this.r , this.color )
getText(this.text ,this.x+ this.r , this.y + this.r ,getRandomColor() )
}
// 空心小球
Ball.prototype.renders = function(){
ctx.beginPath()
ctx.arc(this.x,this.y,this.r,this.color,Math.PI*2,true)
ctx.strokeStyle = this.color
ctx.stroke()
ctx.closePath()
}
// 速度
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
}
function drawLine (x0,y0,x1,y1,width,color){
ctx.beginPath()
ctx.moveTo(x0,y0)
ctx.lineTo(x1,y1)
ctx.strokeStyle = color || "#000"
ctx.lineWdith = width
ctx.stroke()
ctx.closePath()
}
function getXY(min , max){
return (parseInt(Math.random()*(max - min + 1) + min))
}
function getR(r){
return Math.random() * r
}
let barArr = []
for(let i = 0 ; i< 6 ; i++){
let ball = new Ball(getXY(80,400),getXY(80,400),getR(60),getRandomColor(),"","","",arr[i])
barArr.push(ball)
ball.render()
for(let j = 0 ; j < i ; j++){
let prevBall = barArr[j]
drawLine(barArr[i].x , barArr[i].y , prevBall.x ,prevBall.y,"",getRandomColor())
}
}
setInterval(()=>{
ctx.clearRect(0,0,h,w)
for(let i = 0 ; i< barArr.length ;i++){
var barll = barArr[i]
barll.run()
barll.render()
for(let j = 0 ; j < i ; j++){
let prevBall = barArr[j]
drawLine(barArr[i].x , barArr[i].y , prevBall.x ,prevBall.y,"",barArr[i].color)
}
}
},50)
</script>
canvas绘制动画小球连线
最新推荐文章于 2024-01-12 13:42:08 发布