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

Juniper Belmont
  • 3,296
  • 2
  • 18
  • 28
João Pinto
  • 5,521
  • 5
  • 21
  • 35

1 Answers1

1

The issue is that you're setting the CSS style width and height to something other than the canvas's actual width and height. See this answer for more details.

If you really want the canonical source of the canvas's dimensions to be in the CSS file, you could do something like this:

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]);

I hope there's a more elegant way to strip the 'px', but that's the first thing that came to mind.

Community
  • 1
  • 1
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109