<!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>
*{
margin: 0;
padding: 0;
}
</style>
<body>
<div class="box">
<canvas class="canvas" id="canvas"></canvas>
</div>
</body>
<script>
let canvas = document.getElementById("canvas")
// 绘制2d平面,没有3d
let ctx = canvas.getContext('2d')
let w = document.documentElement.clientWidth - 6;
let h = document.documentElement.clientHeight -6;
canvas.width = w
canvas.height = h
// 小球类
function Ball (x, y, r){
/**
* x 坐标
* y 坐标
* r 半径
* color 颜色
* xa x轴速度
* ya y轴速度
* **/
this.x = x
this.y = y
this.r = 30
this.color = '#' + (Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')) //随机颜色
}
// 绘制小球
Ball.prototype.show = function() {
// 绘制
this.r--
yuan(ctx, this.x, this.y, this.r, 0, Math.PI * 2, true, this.color, this.color, "1px")
}
// 生成小球
let ball_array = []
// 鼠标每次滑动,都创建一个新的小球,并绘制
window.onmousemove = function(e) {
// 鼠标滑动的坐标
let x = e.x
let y = e.y
let ball = new Ball(x, y)
ball_array.push(ball)
ball.show()
}
setInterval(function() {
// 删除小球
ctx.clearRect(0, 0, w, h)
for(let i =0; i<ball_array.length;i++) {
// 如果小球半径已经小于0,需要从数组中删除
if(ball_array[i].r <= 0) {
ball_array.splice(i, 1)
}else{
ball_array[i].show()
}
}
}, 10)
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鼠标跟随小球
最新推荐文章于 2024-04-13 17:41:08 发布