0

I'm trying to write a click listener in Javascript that determines whether the user clicked inside a given element (i.e., a polygon or oval drawn on a canvas), but 'this' doesn't refer to an instance of the method's enclosing class, and the element's fields aren't initialized. I'm trying to follow the answer given here: How do I add a simple onClick event handler to a canvas element?

but I don't know where I'm going wrong.

// in the constructor
canvas.addEventListener('click', this.onClick, false);
// after the constructor
onClick(event) {
                const canvas     = this.#canvas; // this somehow refers to the canvas already?
                const elemLeft   = canvas.offsetLeft; // always 0
                const elemTop    = canvas.offsetTop; // always 0
                const x          = event.pageX - elemLeft; // bizarre number
                const y          = event.pageY - elemTop; // bizarre number
                const len        = super.elements.length; // can't find super or elements[]
                for(var i = 0; i < len; i++) {
                        const element = this.#elements[i];
                        const x0      = element[0];
                        const y0      = element[1];
                        const er      = element[2];
                        if (Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)) > er) continue;
                        controller.selectIndex(i);
                        return;
                }
}
  • I added an arrow function and a call to bind(this) to make the correct 'this' appear in the event callback method, as per: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback I then got more reasonable offset values, as per: https://stackoverflow.com/questions/11634770/get-position-offset-of-element-relative-to-a-parent-container But now those offset values seem to be using a different scale than the elements drawn on the canvas. – Innovations Anonymous Jan 11 '20 at 19:36
  • offset scale problem solved. https://stackoverflow.com/questions/4938346/canvas-width-and-height-in-html5 – Innovations Anonymous Jan 16 '20 at 17:44

0 Answers0