我正在尝试从椭圆的中心到边界的随机点画一条线。基本上,我的代码是我前段时间写的一些js代码的复制粘贴。我正在使用画布和香草js。
我的代码:
var o;
function setup() {
createCanvas(500, 500);
o = ellipseGetRandomPoint(250,250,200,300);
}
function draw() {
background(220);
stroke("black");
fill("#333333");
ellipse(250,250,300,400);
stroke("red")
line(250,250,o.pointX, o.pointY);
console.log(o);
fill("#999999");
stroke(0);
ellipse(250,250,200,300);
}
function ellipseGetRandomPoint(centerX, centerY, radiusX, radiusY) {
let o = {};
r = Math.floor(Math.random()*360);
pointX = centerX + radiusX * Math.cos(r*Math.PI / 180);
pointY = centerY + radiusY * Math.sin(r*Math.PI / 180);
o.pointX = Math.floor(pointX);
o.pointY = Math.floor(pointY);
o.r = r;
return o;
}
问题是,该行的某些部分在椭圆之外,我真的不知道为什么,因为抛物线的参数方程似乎还可以,并且该代码的一个非常相似的版本正在工作在我的其他js程序上。
ellipse()
的第三和第四参数是椭圆的宽度和高度,而不是半轴。
因此ellipse()
的参数必须是ellipseGetRandomPoint
而不是150, 200
:
200, 300
o = ellipseGetRandomPoint(250,250,200,300);
请参见示例:
o = ellipseGetRandomPoint(250,250,150,200);
var angle = 0;
function setup() {
createCanvas(500, 500);
}
function draw() {
let o = ellipseGetRandomPoint(250,250,150,200);
angle += 1;
background(220);
stroke("black");
fill("#333333");
ellipse(250,250,300,400);
stroke("red")
line(250,250,o.pointX, o.pointY);
console.log(o);
fill("#999999");
stroke(0);
ellipse(250,250,200,300);
}
function ellipseGetRandomPoint(centerX, centerY, radiusX, radiusY) {
let o = {};
r = Math.floor(Math.random()*360);
r = angle;
pointX = centerX + radiusX * Math.cos(r*Math.PI / 180);
pointY = centerY + radiusY * Math.sin(r*Math.PI / 180);
o.pointX = Math.floor(pointX);
o.pointY = Math.floor(pointY);
o.r = r;
return o;
}