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

I have an HTML5 canvas on a webpage. When the user clicks on the canvas, I would like to get the X and Y coordinates relative to the canvas. I would like to do it in Darth.

+4
source share
2 answers

Dart has a synchronous version if getBoundingClientRect is now, so you no longer need to use the asynchronous version.

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

There are also "offsetX" and "offsetY" in MouseEvent that do the same, but I'm not sure that these fields will be forever because they are not standard.

+3
source

This answer is deprecated, see 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 a bounding click 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); }); 

Then determine the algorithm for shifting from window to canvas.

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

Then attach the click event handler to the canvas:

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

Source: https://habr.com/ru/post/1412151/


All Articles