How to get the coordinates of a user drawn line in canvas

时间:2018-06-04 17:24:15

标签: javascript html canvas html5-canvas

I understand that you can draw lines using the canvas element. What I want to accomplish, is the user selects 2 points on the canvas. Then, using the 2 points I can calculate the equation of this line. However, I have not been able to figure out how I can access the coordinates property of the dots that a user draws on the canvas. How can I accomplish this?

1 个答案:

答案 0 :(得分:0)

If the user needs to click to select the points, you want to look into addEventListnener and the MouseEvent object that is passed into the event handler that you register.

For example:

canvasElement.addEventListener("click", function(event /* MouseEvent */) {
  // now event.clientX and event.clientY have mouse coordinates
});