Get the mouse coordinates when clicking on canvas

后端 未结 2 967
予麋鹿
予麋鹿 2021-01-02 16:27

A common question, but I still need help. I\'m trying to get and store the mouse coordinates when someone clicks within the canvas.

my HTML



        
2条回答
  •  情话喂你
    2021-01-02 16:37

    I am using this piece of code.

    var myCanvas = document.querySelector('#canvas');
    
    myCanvas.addEventListener('click', function(event) {
        var rect = myCanvas.getBoundingClientRect();
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;
        console.log("x: " + x + " y: " + y); 
    }, false);

提交回复
热议问题