欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > canvas基础学习(鼠标点位拖拽)

canvas基础学习(鼠标点位拖拽)

2025/12/12 22:04:50 来源:https://blog.csdn.net/notagoodwriter/article/details/143290558  浏览:    关键词:canvas基础学习(鼠标点位拖拽)

一. 效果

二. 代码

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>* {margin: 0;padding: 0;}body {overflow: hidden;margin: 0;padding: 0;}#div {width: 100%;height: 100vh;}#canvas {width: 100%;height: 100%;background-color: #000;}</style>
</head><body><div id="div"><canvas id="canvas"></canvas></div><script>// 获取元素const canvas = document.getElementById("canvas");const div = document.getElementById("div");// 获取canvas画布const ctx = canvas.getContext("2d");// 获取宽高const w = div.offsetWidth;const h = div.offsetHeight;// 设置宽高canvas.width = w;canvas.height = h;// 是否可以拖拽let isMove = false// 点位对象数组let pointList = [];// 构造点位函数  批量生产点位function Point(x, y, color) {// 点位坐标this.x = x;this.y = y;// 点位颜色this.color = color;// 点位半径this.r = 20;}// 绘制点位函数Point.prototype.draw = function () {ctx.beginPath();ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);ctx.fillStyle = this.color;ctx.fill();}// 鼠标点击事件div.addEventListener("mousedown", (e) => {// 鼠标的坐标let x = e.clientX;let y = e.clientY;// 点位坐标和鼠标坐标的距离for (let i = 0; i < pointList.length; i++) {let point = pointList[i];// 勾股定理判断  鼠标在点位的半径内let distance = Math.sqrt(Math.pow(point.x - x, 2) + Math.pow(point.y - y, 2));if (distance < point.r) {// 将点位放到数组的第一位let obj = pointList[i];pointList[i] = pointList[0]pointList[0] = obj// 开启拖拽isMove = true}}})// 鼠标移动事件div.addEventListener("mousemove", (e) => {// 鼠标的坐标let x = e.clientX;let y = e.clientY;// 判断鼠标是否变为手指let boolean = false;// 鼠标是否在点位的半径内for (let i = 0; i < pointList.length; i++) {let point = pointList[i];let distance = Math.sqrt(Math.pow(point.x - x, 2) + Math.pow(point.y - y, 2));if (distance < point.r) {// 鼠标变为手指boolean = true}}// 拖拽点位(鼠标点击时已经将拖拽点位提到了点位数组的第一个所以只需要将第一个点位的坐标改为鼠标的坐标即可)if (isMove) {pointList[0].x = x;pointList[0].y = y;// 清除画布  ctx.clearRect(0, 0, w, h);// 重新绘制点位for (let i = 0; i < pointList.length; i++) {if (i !== 0) {let point = pointList[i];point.draw();}}// 最后绘制的点位层级最高pointList[0].draw();}// 鼠标是否变为手指if (boolean) {div.style.cursor = 'pointer'} else {div.style.cursor = 'default'}})// 鼠标抬起事件div.addEventListener("mouseup", (e) => {// 关闭拖拽isMove = false})// 随机生成点位  随机颜色  随机坐标for (let i = 0; i < 10; i++) {let point = new Point(Math.random() * w, Math.random() * h, "hsl(" + Math.random() * 360 + ", 100%, 50%)");pointList.push(point);point.draw();}</script>
</body></html>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词