canvas translate scale变换后获取鼠标位置

27 阅读1分钟

技术点

  • translate(x,y) :移动的原点

  • scale(x,y) :缩放坐标系。x:canvas坐标系水平缩放的比例,y:canvas坐标系垂直缩放的比例。

  • bound = ctx.getBoundingClientRect():获取画布边界。

  • x = e.pageX - bound.left; y = e.pageY - bound.top。获取鼠标在画布上的坐标位置(x,y)。



translate(canvas_w/2,canvas_h/2)把坐标系原点移动到canvas中心,然后scale(unit,unit)对坐标系缩小0.5倍,在(w, h)处绘画一个点,判断鼠标是否在(w,h)处。*

判断方法:

  1. x = e.pageX - bound.left;y = e.pageY - bound.top。(x,y)坐标为原坐标系的坐标。
  2. (w,h)在转换后坐标系位置需要转换为原坐标系的位置(w',h')。 w' = w * unit + canvas_w/2 + bound.left, h' = h * unit + canvas_h/2 + bound.top。
  3. 然后判断(x,y)是否等于(w',h')。即x == w',y == h'。
  <canvas id="canvas" ref="canvas"></canvas>
let ctx = canvas.getContext('2d'); 
const canvas = ref<HTMLCanvasElement | null>(null);
let canvas_w = canvas.value.offsetWidth;
let canvas_h = canvas.value.offsetHeight;
let bound = canvas.value.getBoundingClientRect();
ctx.clearRect(0, 0, canvas_w, canvas_h);
ctx.translate((canvas_w) / 2, (canvas_h) / 2);
ctx.scale(_unit, _unit);
ctx.save();
// 设置画笔颜色
ctx.strokeStyle = 'green';

// 开始路径
ctx.beginPath();

// 圆心位置 (x, y), 半径, 起始角度, 结束角度, 方向
ctx.arc(w, h, 2, 0, Math.PI, false);

// 描边
ctx.stroke();

ctx.restore();

canvas.value.addEventListener('mousemove',(e: any) => {
   let mouseX = e.pageX;
   let mouseY = e.pageY;
   let  w1 = w * unit + canvas_w/2 + bound.left;
   let h1 = h * unit + canvas_h/2 + bound.top;
   if (mouseX == w1 && mouseY == h1) {
    console.log('鼠标在(w,h)处)。
    }
 })