我需要在椭圆内添加大量的点。我试图修改来自这个问题的被接受解决方案的代码,该解决方案设置为使用一个圆(宽度和高度相同),而不是椭圆。它还是通过HTML <canvas>
元素实现的,而我需要使用p5.js
使其工作。
以下是我用于<canvas>
元素的代码。它似乎运行良好,我可以随意调整椭圆的大小和位置,并且无论如何都会在其中显示所有点。
function ellipse(context, cx, cy, rx, ry){
context.save(); // save state
context.beginPath();
context.translate(cx-rx, cy-ry);
context.scale(rx, ry);
context.arc(1, 1, 1, 0, 2 * Math.PI, false);
context.restore(); // restore to original state
context.stroke();
}
var canvas = document.getElementById("thecanvas");
var ctx = canvas.getContext('2d'),
count = 1000, // number of random points
cx = 300,
cy = 200,
w = 50,
h = 49,
radius = w;
ctx.fillStyle = '#CCCCCC';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ellipse(ctx, cx, cy, w, h);
// create random points
ctx.fillStyle = '#ffffff';
function dots() {
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( ((Math.sqrt(pt_radius_sq) * Math.cos(pt_angle) ) + cx), (((Math.sqrt(pt_radius_sq) * Math.sin(pt_angle))/(w/h)) + cy), 2, 2);
count--;
}
}
dots();
<canvas id="thecanvas" width="800" height="800"></canvas>
由于某些原因,我认为很容易移植到p5.js
的内容却无法正常工作。点似乎被包含在与定义相同形状的椭圆中,但比例似乎有问题,我无法确定是什么原因导致的。您可以在https://editor.p5js.org/dpassudetti/sketches/YRbLuwoM2中查看实际效果- p5.js
代码也已粘贴如下:
var count = 1000, // number of random points
cx = 300,
cy = 200,
w = 50,
h = 49,
radius = w;
function setup() {
createCanvas(800, 800);
function dots() {
fill('green');
stroke('green');
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);
square(
Math.sqrt(pt_radius_sq) * Math.cos(pt_angle) + cx,
(Math.sqrt(pt_radius_sq) * Math.sin(pt_angle)) / (w / h) + cy,
2,
2
);
count--;
}
}
fill("#CCCCCC");
ellipse(cx, cy, w, h);
dots();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
如果有人能看出是什么导致了 p5.js
版本的比例不正确,并且不介意指导我正确的方向,我将非常感激。
ellipse(cx, cy, w * 2, h * 2);
吗? - ggorlen