You need to enable JavaScript to run this app. 如何检测HTML Canvas中绘制的圆盘区域内的点击事件?
优惠活动
大模型
产品
解决方案
定价
更多

如何检测HTML Canvas中绘制的圆盘区域内的点击事件?

实现方案

核心思路是把当前显示圆盘的位置、半径信息存储在全局变量中,每次点击时判断点击坐标是否落在圆盘范围内,只有命中时才执行刷新逻辑。

具体修改点

  • 新增全局变量存储当前圆盘的圆心坐标、半径,避免点击事件中无法获取上一次绘制的圆盘位置
  • 点击事件中先计算点击位置相对于Canvas的实际坐标
  • 通过勾股定理计算点击位置和圆心的距离,判断是否命中圆盘
  • 初始加载时先绘制第一个圆盘,避免页面刚打开无交互目标

修改后完整代码

// 全局变量存储当前圆盘的信息
let currentCircle = {
  x: 0,
  y: 0,
  radius: 25
}
const elem = document.getElementById('myCanvas');
const c = document.getElementById("myCanvas");
const ctx = c.getContext("2d");
const myColors = ['blue', 'red', 'green', 'yellow', 'black', 'maroon'];

// 初始化绘制第一个圆盘
drawNewCircle();

elem.onclick = function(e) {
  // 计算点击位置相对于Canvas的坐标
  const rect = c.getBoundingClientRect();
  const clickX = e.clientX - rect.left;
  const clickY = e.clientY - rect.top;

  // 计算点击位置到圆心的距离
  const distance = Math.sqrt(
    Math.pow(clickX - currentCircle.x, 2) + Math.pow(clickY - currentCircle.y, 2)
  );

  // 只有距离小于等于半径才说明点中了圆盘
  if (distance <= currentCircle.radius) {
    drawNewCircle();
  }
}

// 封装绘制新圆盘的公共方法
function drawNewCircle() {
  // 清空画布
  ctx.clearRect(0,0,1000,750);
  // 计算新圆盘的随机坐标
  const posx = Math.floor(Math.random() * 950);
  const posy = Math.floor(Math.random() * 625);
  // 更新全局存储的圆盘坐标
  currentCircle.x = posx + 25;
  currentCircle.y = posy + 25;
  // 绘制新圆盘
  ctx.beginPath();
  ctx.arc(currentCircle.x, currentCircle.y, currentCircle.radius, 0, 2 * Math.PI);
  ctx.stroke();
  const selectedcolor = myColors[Math.floor(Math.random() * myColors.length)];
  ctx.fillStyle = selectedcolor;
  ctx.fill();
}

逻辑说明

  • 把绘制圆盘的逻辑封装成公共方法,避免重复代码
  • 每次绘制新圆盘后都会更新全局变量中存储的圆心坐标,确保下次点击判断的是当前显示圆盘的位置
  • 点击坐标计算时使用getBoundingClientRect适配Canvas在页面中的偏移,避免页面存在滚动或边距时判断不准的问题

内容的提问来源于stack exchange,提问作者Esjee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 21:06:02