开发者

Use JavaScript to select point on a circle

Is there a way to use JavaScript to select a point on an image of a wheel, and save the point from maybe 0-36开发者_开发问答0?


You can use trigonometry to find the point on a circle if you know the circle's radius:

var x = Math.cos(pointAngleInRadians) * radius;
var y = Math.sin(pointAngleInRadians) * radius;

If the circle is centered on a point such as (10, 20) you would need to add these values to x and y to get accurate coordinates.


Update

The article Click image and get coordinates with JavaScript explains how you can call a function when a user clicks on a image, and have that function figure out the coordinates.

Here are some high-level notes of how you might use this to figure out the angle (0 - 360 degrees) that they clicked:

  • Knowing the coordinates of the center of each circle and the coordinates the user clicked on, you can calculate the radius using the distance between points, calculated by:

Use JavaScript to select point on a circle

  • Then you can use trig equations above to calculate the angle of the point on each circle.

  • Assuming each circle has a width, you could calculate the coordinates of the point with the same angle/radius at the outer and inner edges of each tire.

  • Compare the inner/outer edge values to the point the user clicked on to see if the user clicked within the tire's bounds. For both x and y you will need two cases for each half of the circle - for example, the following is only valid for 180 degrees xInner <= x <= xOuter, and then for the remaining 180 degrees xInner >= x >= xOuter.

  • After the previous step, if the point is on one of the tires, then you have the angle. You may need to convert it from radians to degrees before storing it:

angle in degrees = angle in radians * 180 / Pi


Found out, quite by trial and errors (!), a possible centuries old shortcut to draw an ellipse.

The Pythagoras constant : √2

By knowing the center [x,y], and the radius [x,y] (usually coming from two mouse click), basically by multiplicating the hypotenuse by 1.41 constant Math.SQRT2 you get the closest point on the circle perimeter.

For some iframe reasons, this doesn't behave precisely well on the SO embeded code snippets below, but no issues otherwise.

const pX = 150 // Center X
const pY = 55 // Center Y
let sX,sY

let n = document.createElementNS("http://www.w3.org/2000/svg", 'ellipse')

svg.addEventListener('mousemove', function(e){
  sX = e.pageX
  sY = e.pageY
  n.setAttribute("cx",pX)
  n.setAttribute("cy",pY)
    
  let rx = Math.hypot(pX - sX, pY - sY) * Math.SQRT2
  let ry = Math.abs((pY - sY))

  n.setAttribute("rx",rx)
  n.setAttribute("ry",ry)

  svg.appendChild(n)
  
})
<svg id="svg" width="100%" height="600"></svg>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜