How to add an onClick event handler to the canvas form in Elm?

Can I add an onClick event handler in Graphics.Collage.square?

I would like to know the relative position of the click.

In Javascript, I could do something like this :

var canvas = document.getElementById('canvas');
var canvasPosition = {
  x: canvas.offsetLeft,
  y: canvas.offsetTop
};

canvas.addEventListener('click', function(event) {
  console.log(event.x - canvasPosition.x, event.y - canvasPosition.y);
}, false);

Is it possible to do something like this in Elm?

An example will be appreciated.

+4
source share
2 answers

In Elm, using Canvas rendering, you must use the signal Mouse.clicksand respond to signal changes. Here is an example that will work:

import Graphics.Element exposing (Element, show)
import Mouse

clicks : Signal (Int, Int)
clicks =
  Signal.sampleOn Mouse.clicks Mouse.position

main : Signal Element
main =
  Signal.map show clicks

In essence, these Mouse.clicksare the actual “events” that interest us, so when this happens, we “wake up” the signal Mouse.positionto get the position of the click.

Signal.sampleOn , (, ) , (, ).

, , show main.

http://elm-lang.org/try, , , .

+2

. , .

, - ( , y Graphics.Collage , y ), . , , .

elm-svg, DOM, mouseenter, , , , . (sniff) D3.js SVG.

0

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


All Articles