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

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


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


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.