How do I get the coordinates of a mouse click on a canvas element?

后端 未结 22 2427
忘掉有多难
忘掉有多难 2020-11-21 23:56

What\'s the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?

No

22条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 00:36

    ThreeJS r77

    var x = event.offsetX == undefined ? event.layerX : event.offsetX;
    var y = event.offsetY == undefined ? event.layerY : event.offsetY;
    
    mouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;
    mouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;
    

    After trying many solutions. This worked for me. Might help someone else hence posting. Got it from here

提交回复
热议问题