4

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 computer I've tried.

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

Community
  • 1
  • 1
Sled
  • 18,541
  • 27
  • 119
  • 168

1 Answers1

5

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.

jonobr1
  • 1,013
  • 2
  • 11
  • 22