Sir*_*Sir 6 javascript random geometry canvas
我有一个基本的JSFiddle,我希望在圆圈内绘制随机点.
但我不知道如何限制圆圈内的点数.
这就是我目前拥有的:
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = 150,
cy = 150,
radius = 148;
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(canvas.width/2, canvas.height/2, radius, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = '#00000';
ctx.fill();
// create random points
ctx.fillStyle = '#ffffff';
while(count) {
// randomise x:y
ctx.fillRect(x + canvas.width/2, y + canvas.height/2, 2, 2);
count--;
}
Run Code Online (Sandbox Code Playgroud)
我如何生成随机(x,y)坐标来绘制圆内的随机点?
我现在的小提琴:http://jsfiddle.net/e8jqdxp3/
Max*_*ter 14
要在圆圈中随机绘制点,您可以从radius平方中选择一个随机值,然后从它的平方根中选取一个随机角度,并将极坐标转换为矩形.平方/平方根步骤确保我们得到均匀分布(否则大多数点将接近圆的中心).
因此,绘制圆中随机点的公式如下,其中r'是0和r 2之间的随机值,θ是0到2π之间的随机值:
结果截图:
现场演示:
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = 150,
cy = 150,
radius = 148;
ctx.fillStyle = '#CCCCCC';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#000000';
ctx.beginPath();
ctx.moveTo(cx, cy);
ctx.arc(canvas.width / 2, canvas.height / 2, radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
// create random points
ctx.fillStyle = '#ffffff';
while (count) {
var pt_angle = Math.random() * 2 * Math.PI;
var pt_radius_sq = Math.random() * radius * radius;
var pt_x = Math.sqrt(pt_radius_sq) * Math.cos(pt_angle);
var pt_y = Math.sqrt(pt_radius_sq) * Math.sin(pt_angle);
ctx.fillRect(pt_x + canvas.width / 2, pt_y + canvas.width / 2, 2, 2);
count--;
}Run Code Online (Sandbox Code Playgroud)
<canvas id="thecanvas" width="400" height="400"></canvas>Run Code Online (Sandbox Code Playgroud)
JSFiddle版本:https://jsfiddle.net/qc735bqw/