Seth Ladd
Seth Ladd

Reputation: 120439

How do you get the X and Y from a mouse click on an HTML5 canvas in Dart?

I have an HTML5 canvas on a web page. When a user clicks on the canvas, I'd like to get the X and Y coordinates, relative to the canvas. I'd like to do this in Dart.

Upvotes: 4

Views: 1917

Answers (2)

Seth Ladd
Seth Ladd

Reputation: 120439

This answer is out of date, see the accepted answer above

Create a simple Point class:

class Point {
  final int x;
  final int y;

  Point(this.x, this.y);
}

Import dart:html library:

import 'dart:html';

First step, get the client bounding rect for the canvas:

Point clientBoundingRect;
Future<html.ElementRect> futureRect = ctx.canvas.rect;

futureRect.then((html.ElementRect rect) {
  clientBoundingRect = new Point(rect.bounding.left, rect.bounding.top);
});

Next, define the offset algorithm from the window to the canvas.

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

Next, attach the click event handler to the canvas:

ctx.canvas.on.click.add((e) {
    click = getXandY(e);
});

Upvotes: 6

bp74
bp74

Reputation: 111

Dart has a synchronous version if getBoundingClientRect now, so you don't have to use the asynchronous version anymore.

var clientRect = ctx.canvas.getBoundingClientRect();

ctx.canvas.on.click.add((e) {
  var x = e.clientX - clientRect.left;
  var y = e.clientY - clientRect.top;
});

There is also the "offsetX" and "offsetY" getters in MouseEvent which do the same thing, but i'm not sure if those fields will be their forever because they are not in the standard.

Upvotes: 3

Related Questions