canvas鼠标跟随小球

请添加图片描述

<!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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值