admin管理员组

文章数量:1417549

I have drawn a shape using two.js and I want to write code to handle click events on that shape. Not the canvas, but on the shape itself.

front_left.domElement = $('#two-' + front_left.id)
    .css('cursor', 'pointer')
    .click(function(e){
        alert("Hello World!");
    });

This code taken from an answer that seems like it should work:

circle.domElement = $('#two-' + circle.id)
  .css('cursor', 'pointer')
  .click(function(e) {
    circle.fill = getNonMainRandomColor(getRandomColor());
  });

but it doesn't work for me using the latest JQuery and the latest two.js, and it also doesn't seem to work in the example, since the code reads as if clicking on the circles was supposed to make the colour changes but nothing happens on any browser or puter I've tried.

So, how can I capture and respond to click events of shapes/groups drawn with two.js?

I have drawn a shape using two.js and I want to write code to handle click events on that shape. Not the canvas, but on the shape itself.

front_left.domElement = $('#two-' + front_left.id)
    .css('cursor', 'pointer')
    .click(function(e){
        alert("Hello World!");
    });

This code taken from an answer that seems like it should work:

circle.domElement = $('#two-' + circle.id)
  .css('cursor', 'pointer')
  .click(function(e) {
    circle.fill = getNonMainRandomColor(getRandomColor());
  });

but it doesn't work for me using the latest JQuery and the latest two.js, and it also doesn't seem to work in the example, since the code reads as if clicking on the circles was supposed to make the colour changes but nothing happens on any browser or puter I've tried.

So, how can I capture and respond to click events of shapes/groups drawn with two.js?

Share Improve this question edited Oct 8, 2024 at 7:51 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Apr 23, 2015 at 3:11 SledSled 19k27 gold badges124 silver badges172 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Thanks for the message. The reason this answer doesn't work anymore is because two.js has changed since then. I've added an example here. The gist of it is that:

  1. Use the svg renderer
  2. Whenever you create a shape it will have a private property _renderer
  3. You can access the elem which is its corresponding dom element
  4. But! make sure that the renderer has updated before you access it

e.g:

var shape = two.makeCircle(two.width / 2, two.height / 2, 50);
two.update();
shape._renderer.elem.addEventListener('click', handler, false);

And, if you're feeling adventurous you can mix renderers like in this example.

本文标签: javascriptHow to capture a click event on a shape or groupStack Overflow