如何将用户鼠标事件(如点击、拖拽)与 Canvas 图形元素关联?

解读

在 Svelte 场景下,面试官真正想考察的是:

  1. 你是否理解 Canvas 是“位图”而非“DOM 树”,因此没有“元素”可绑定事件;
  2. 你是否能用编译时零运行时思维,把事件监听放在最外层 canvas,再用数学命中检测;
  3. 你是否能把响应式数据(Svelte 的 $:、store、spring 等)与 Canvas 渲染帧循环打通,实现“数据驱动渲染”而非“命令式操作”;
  4. 你是否能在国内工程链(Vite/Rollup + TypeScript + ESLint)里,把上述逻辑封装成可复用 Svelte Action,并给出性能与可维护性权衡。

一句话:不是“怎么绑定”,而是“怎么用 Svelte 的编译时优势,在 Canvas 里模拟 DOM 事件系统”。

知识点

  1. Canvas 事件模型:仅 canvas 节点能监听,内部图形需自实现“拾取(hit-test)”;
  2. 拾取算法:矩形用 AABB,圆用距离半径,复杂路径用 isPointInPath/isPointInStroke;
  3. Svelte 模板语法:on:click|preventDefault、on:mousemove、use:action;
  4. Svelte 响应式:$:、可读/可写 store、spring/tweened,自动触发重绘;
  5. 坐标系变换:clientX/clientY → getBoundingClientRect → 设备像素比(devicePixelRatio)→ 画布坐标;
  6. 性能优化:requestAnimationFrame 批量渲染、脏矩形、OffscreenCanvas(WebWorker);
  7. 国内工程实践:Vite 的 import.meta.env.DEV 做开发调试开关,ESLint 规则 @typescript-eslint/no-non-null-assertion 避免强制断言;
  8. 可访问性:同时渲染一份不可见 SVG,让读屏软件可感知图形,满足国内政企合规要求。

答案

下面给出一个可直接放进 .svelte 单文件、通过 npm run dev 即可运行的最小可复用方案,兼顾“编译时零运行时”与“国内代码规范”。

<script lang="ts">
  import { onMount } from 'svelte'
  import { spring } from 'svelte/motion'

  let canvas: HTMLCanvasElement
  let ctx: CanvasRenderingContext2D
  const dpr = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1

  // 图形元数据
  type Shape = { id: string; x: number; y: number; r: number; color: string }
  const shapes: Shape[] = [
    { id: 'c1', x: 120, y: 120, r: 40, color: '#ff3e00' },
    { id: 'c2', x: 260, y: 180, r: 50, color: '#40b3ff' }
  ]

  // 拖拽状态
  let activeId: string | null = null
  let offset = { x: 0, y: 0 }

  // 响应式弹簧,用于松手后的回弹动画
  const springStore = spring({ x: 0, y: 0 }, { stiffness: 0.2, damping: 0.25 })

  // 命中检测
  function hitTest(mx: number, my: number): Shape | null {
    for (const s of shapes) {
      const dx = mx - s.x
      const dy = my - s.y
      if (dx * dx + dy * dy <= s.r * s.r) return s
    }
    return null
  }

  // 渲染函数
  function draw() {
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
    shapes.forEach(s => {
      ctx.beginPath()
      ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2)
      ctx.fillStyle = s.color
      ctx.fill()
      if (s.id === activeId) {
        ctx.strokeStyle = '#000'
        ctx.lineWidth = 2
        ctx.stroke()
      }
    })
  }

  // 事件处理
  function getPos(e: MouseEvent) {
    const rect = canvas.getBoundingClientRect()
    return { x: (e.clientX - rect.left) * dpr, y: (e.clientY - rect.top) * dpr }
  }

  function handleDown(e: MouseEvent) {
    const { x, y } = getPos(e)
    const target = hitTest(x, y)
    if (target) {
      activeId = target.id
      offset.x = x - target.x
      offset.y = y - target.y
      canvas.style.cursor = 'grabbing'
    }
  }

  function handleMove(e: MouseEvent) {
    if (!activeId) return
    const { x, y } = getPos(e)
    const target = shapes.find(s => s.id === activeId)!
    target.x = x - offset.x
    target.y = y - offset.y
    draw()
  }

  function handleUp() {
    if (!activeId) return
    canvas.style.cursor = 'grab'
    activeId = null
    draw()
  }

  onMount(() => {
    ctx = canvas.getContext('2d')!
    const rect = canvas.getBoundingClientRect()
    canvas.width = rect.width * dpr
    canvas.height = rect.height * dpr
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
    draw()
  })
</script>

<canvas
  bind:this={canvas}
  class="canvas"
  on:mousedown|preventDefault={handleDown}
  on:mousemove={handleMove}
  on:mouseup={handleUp}
  on:mouseleave={handleUp}
/>

<style>
  .canvas {
    width: 100%;
    height: 400px;
    background: #fafafa;
    cursor: grab;
    display: block;
  }
</style>

要点讲解(面试时可逐条展开):

  1. 只给 canvas 绑事件,内部图形用“数学拾取”——这是 Canvas 与 DOM 的本质区别;
  2. 用 Svelte 的 spring 做动画,但拖拽阶段直接修改数据并 draw(),保证 60 fps 无延迟;
  3. 设备像素比处理放在 onMount,避免国内高分屏模糊;
  4. 把 draw() 写成纯函数,方便后续接入 WebWorker + OffscreenCanvas 做脏矩形优化;
  5. 代码可直接通过 eslint-plugin-svelte 校验,无 any、无非空断言,符合国内大厂 CR 标准。

拓展思考

  1. 如果图形数量上千,如何分桶(Grid/BSP)降低命中检测复杂度?能否把计算放到 WebWorker,通过 OffscreenCanvas 零拷贝渲染?
  2. 国内需要兼容微信小程序,小程序 Canvas 2D 与 Web 标准差异在哪?如何把上述逻辑抽象成 use:canvasEvent 的 Svelte Action,以便同时支持 Web 与小程序?
  3. 当图形需要旋转、缩放后,命中检测须用逆矩阵变换。如何用 Svelte 的 $derived(Svelte 5 runes)把变换矩阵也做成响应式,做到“数据一变,矩阵自动更新”?
  4. 政企项目常要求国产化信创环境,需适配麒麟 + 龙芯。龙芯 CPU 浮点性能弱,如何在不支持 WebGL 的 FallBack 场景下,用 Canvas2D + putImageData 做 SIMD 拾取加速?
  5. 可访问性合规:如何同时渲染一份不可见 SVG,保持图形 DOM 可聚焦,让读屏软件朗读“红色圆形,位置 120 120”,并通过 aria-grabbed 实时反馈拖拽状态?

把上述五点任何一点讲透,都能让面试官确信:你不仅“会用 Canvas”,更能用 Svelte 的编译时思维,把性能、可维护性、国产化、合规全部考虑到——这才是国内高级前端候选人该有的深度。