微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在圆圈内随机绘制点的最简单方法

我有一个基本的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,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--;
}

我如何生成随机(x,y)坐标来绘制圆内的随机点?

我现在的小提琴:http://jsfiddle.net/e8jqdxp3/

解决方法

要在圆中随机绘制点,您可以从半径平方中选择一个随机值,然后从中取平方根,选择一个随机角度,并将极坐标转换为矩形.平方/平方根步骤确保我们得到均匀分布(否则大多数点将接近圆的中心).

因此,绘制圆中随机点的公式如下,其中r’是0和r2之间的随机值,θ是0到2π之间的随机值:

结果截图:

现场演示:

var canvas = document.getElementById("thecanvas");

var ctx = canvas.getContext('2d'),radius = 148;

ctx.fillStyle = '#CCCCCC';
ctx.fillRect(0,canvas.width,canvas.height);

ctx.fillStyle = '#000000';

ctx.beginPath();
ctx.moveto(cx,cy);
ctx.arc(canvas.width / 2,canvas.height / 2,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);
    count--;
}
<canvas id="thecanvas" width="400" height="400"></canvas>

JSfiddle版本:https://jsfiddle.net/qc735bqw/

原文地址:https://www.jb51.cc/js/155616.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐