0

The following code attempts to draw an image from a button selected in a toolbar into a canvas at the mouse position. Based on the printed coordinates the position is correctly calculated, however the images get placed in the wrong place. The code:

import 'dart:html';

class Test {
  ImageElement toolbar_selected_element = null;
  CanvasElement canvas;
  num mouseX = null, mouseY = null;

  void main() {
    canvas = query("#canvas");
    canvas.onClick.listen(canvas_OnClick);

    for (var toolbutton in queryAll('.toolbutton')) {
      toolbutton.onClick.listen((e) => toolbar_selected_element = query("#${e.target.id}"));
    }
  }

  void canvas_OnClick(MouseEvent event) {
    num x,y;
    var clientBoundingRect = canvas.getBoundingClientRect();
    mouseX = event.clientX - clientBoundingRect.left;
    mouseY = event.clientY - clientBoundingRect.top;
    window.requestAnimationFrame(draw);
  }

  void draw(num _) {
    CanvasRenderingContext2D context = canvas.context2d;
    context.clearRect(0, 0, canvas.width, canvas.height);
    if(toolbar_selected_element!= null   && mouseX != null && mouseY != null) {
      print("$mouseX $mouseY");
      context.drawImage(toolbar_selected_element, mouseX, mouseY);
    }
  }
}

void main() {
  new Test().main();
}

The corresponding html file can be found at: https://github.com/joaompinto/SVGDropper/blob/master/web/svgdropper.html

4

1 回答 1

1

问题是您正在设置 CSS 样式width以及height画布实际宽度和高度以外的其他内容。有关更多详细信息,请参阅此答案

如果您真的希望画布尺寸的规范来源位于 CSS 文件中,您可以执行以下操作:

void main() {
  canvas = query("#canvas");
  canvas.width = int.parse(canvas.getComputedStyle().width.split('px')[0]);
  canvas.height = int.parse(canvas.getComputedStyle().height.split('px')[0]);

我希望有一种更优雅的方式来去除“px”,但这是我首先想到的。

于 2013-04-19T21:44:25.150 回答