Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 219
Seth Ladd Avatar asked Jan 16 '23 17:01

Seth Ladd


2 Answers

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);
});
like image 82
Seth Ladd Avatar answered Jan 30 '23 20:01

Seth Ladd


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.

like image 24
bp74 Avatar answered Jan 30 '23 18:01

bp74