我们如何从onClick事件中获取鼠标画布相对x,y坐标?

时间:2013-04-19 19:31:05

标签: canvas dart

我从https://github.com/sethladd/bad-aliens-dart/blob/master/web/Game.dart找到了以下代码:

    ClientRect rect = ctx.canvas.getBoundingClientRect();
    clientBoundingRect = new GamePoint(rect.left, rect.top);
...
    GamePoint getXandY(e) {
      num x =  e.clientX - clientBoundingRect.x - (ctx.canvas.width/2);
      num y = e.clientY - clientBoundingRect.y - (ctx.canvas.height/2);
      return new GamePoint(x, y);
    }

我已经测试但是它没有计算画布中正确的鼠标位置。

1 个答案:

答案 0 :(得分:2)

CanvasElement.getBoundingRect()现在返回Rect而不是ClientRect。否则,代码似乎适合我。

更新:请注意,Bad Aliens将原点放置在Canvas的中心。也许你想把它留在左上角?如果是这样,那么不要减去画布尺寸的一半:

GamePoint getXandY(e) {
  num x =  e.clientX - clientBoundingRect.x;
  num y = e.clientY - clientBoundingRect.y;
  return new GamePoint(x, y);
}