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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With