javascript中是否有一种方法可以绘制x,y坐标,使它们分成圆形而不是方形?
例如,如果我有以下代码:
circleRadius = 100;
context.drawImage(img_elem, dx, dy, dw, dh);
我需要找出落在100像素圆圈内的x,y值的组合。
谢谢!
答案 0 :(得分:6)
x^2 + y^2 = r^2
定义,在您的情况下等于100 ^ 2 = 10000 y^2 = 10000 - x^2
,因此选择了x和y = +/-sqrt(10000 - x^2)
的点会在圆圈上显示。修改强> 在JS中:
var radius = 100;
x = Math.random() * 2 * radius - radius;
ylim = Math.sqrt(radius * radius - x * x);
y = Math.random() * 2 * ylim - ylim;
另一个修改: a jsFiddle Example
答案 1 :(得分:2)
不确定你对javascript的意思,但
x = R*cos(theta)
和y = R*sin(theta)
是圆的笛卡尔点。 R是当然的半径,theta是从0到2 * Pi的角度。
答案 2 :(得分:2)
如果您想要等分布坐标,最好选择
var radius = 100
var center_x = 0
var center_y = 0
// ensure that p(r) ~ r instead of p(r) ~ constant
var r = radius*Math.sqrt(Math.random(1))
var angle = Math.sqrt(2*Math.PI)
// compute desired coordinates
var x = center_x + r*Math.cos(angle);
var x = center_y + r*Math.sin(angle);
如果您想要更多靠近中间的点,请使用
var r = radius*Math.random(1)
代替。
答案 3 :(得分:0)
不确定这是否是正确的JavaScript代码,但是这样:
for (x = -r; x < r; x++) {
for (y = -r; x < r; y++) {
if ((x * x + y * y) < (r * r)) {
// This x/y coordinate is inside the circle.
// Use <= if you want to count points _on_ the circle, too.
}
}
}
答案 4 :(得分:0)
我将此作为解决方案发布,因为此问题是Google中唯一相关的结果。
我的问题/问题是如何在x
和y
不会超过r
的圈子中添加笛卡尔坐标。
示例:
解决方案
// The scale of the graph to determine position of plot
// I.E. If the graph visually uses 300px but the values only goto 100
var scale = 100;
// The actual px radius of the circle / width of the graph
var radiusGraph = 300;
// Plot the values on a cartesian plane / graph image
var xCart = xVal * radiusGraph;
var yCart = yVal * radiusGraph;
// Get the absolute values for comparison
var xCartAbs = Math.abs( xCart );
var yCartAbs = Math.abs( yCart );
// Get the radius of the cartesian plot
var radiusCart = Math.sqrt( xCart * xCart + yCart * yCart );
// Compare to decide which value is closer to the limit
// Once we know, calculate the largest possible radius with the graphs limit.
// r^2 = x^2 + y^2
if ( xCartAbs > yCartAbs ) { // Less than 45°
diff = scale / xCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( yCartAbs * diff, 2) );
} else if ( yCartAbs > xCartAbs ) { // Greater than 45°
diff = scale / yCartAbs;
radiusMaximum = Math.sqrt( radiusGraph * radiusGraph + Math.pow( xCartAbs * diff, 2) );
} else { // 45°
radiusMaximum = Math.sqrt( 2 * ( radiusGraph * radiusGraph ) );
}
// Get the percent of the maximum radius that the cartesian plot is at
var radiusDiff = radiusCart / radiusMaximum;
var radiusAdjusted = radiusGraph * radiusDiff;
// Calculate the angle of the cartesian plot
var theta = Math.atan2( yCart, xCart );
// Get the new x,y plot inside the circle using the adjust radius from above
var xCoord = radiusAdjusted * Math.cos( theta );
var yCoord = radiusAdjusted * Math.sin( theta );