如何在Elm中的画布形状上添加onClick事件处理程序? [英] How to add an onClick event handler to a canvas shape in Elm?

查看:58
本文介绍了如何在Elm中的画布形状上添加onClick事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Graphics.Collage.square 中添加onClick事件处理程序?

Is it possible to add an onClick event handler to Graphics.Collage.square?

想知道点击的相对位置。

I'd like to know the relative position of the click.

在Javascript中,我可以做类似

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 that possible to do something similar in Elm?

示例将不胜感激。

推荐答案

在榆木中,使用Canvas渲染,您应该使用 Mouse.clicks 信号并对信号的变化做出反应。这是一个如何运行的示例:

In Elm, using the Canvas rendering, you should use the Mouse.clicks signal and react to changes in the signal. Here's a runnable example of how that would 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

本质上, Mouse.clicks 是我们感兴趣的实际事件,因此无论何时发生,我们都会对 Mouse.position 信号进行采样以获取点击位置。

In essence, Mouse.clicks are the actual "events" we are interested in, so whenever one happens, we "sample" the Mouse.position signal to get the click position.

Signal.sampleOn 会产生一个信号,该信号会用第二个参数signal的值进行更新(此处为,即鼠标的位置),只要第一个参数信号发生变化(此处是鼠标单击)。

Signal.sampleOn produces a signal that updates with the value of the second parameter signal (here, the mouse position) whenever there is a change in the first parameter signal (here, the mouse clicks).

现在,为了显示结果,我们也将位置映射到 main 中的 show 函数。

Now, just to get the result showing, we are also mapping the position to the show function in main.

您也可以将此代码粘贴到 http://elm-lang.org/try ,进行编译,然后尝试单击右侧以查看其工作原理。

You can also paste this code to http://elm-lang.org/try, compile and try clicking the right-hand side to see it working.

这篇关于如何在Elm中的画布形状上添加onClick事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆