我试图在 Canvas 上添加许多飞点,当它们之间的距离在 0 到 300 之间时,这些飞点通过一条线相互连接,并且线的不透明度根据它们之间的距离而变化。正如你所看到的,我已经用两个点完成了所有这些工作。但是,我现在面临两个问题。
第一个问题 - 如果我想添加 15 个椭圆,我或多或少必须复制每个新椭圆的代码。我相当确定这不是这样做的方法。
第二个问题是我对哪些点应该相互连接进行硬编码。我希望每个点都连接到附近的每个点,但是,我不确定如何准确地做到这一点。
var el1 = {
x: 100,
y: 100,
width: 5,
height: 5
};
var el2 = {
x: 300,
y: 300,
width: 5,
height: 5
};
var speed = 2;
var opacity = 0;
var xdirection = 1;
var ydirection = 1;
function setup() {
createCanvas(windowWidth, windowHeight - 4);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight - 4);
}
function draw() {
background(51, 51, 51);
fill(55, 90, 80);
noStroke();
ellipse(el1.x, el1.y, el1.width, el1.height);
ellipse(el2.x, el2.y, el2.width, el2.height);
el1.x = el1.x + speed * xdirection;
el1.y = el1.y + speed * ydirection;
if (el1.x > windowWidth || el1.x < 5) {
xdirection *= -1;
}
if (el1.y > windowHeight || el1.y < 5) {
ydirection *= -1;
}
if (dist(el1.x,el1.y,el2.x,el2.y) < 300) {
var opacity = map(dist(el1.x,el1.y,el2.x,el2.y),0, 300, 255, 0);
stroke(55, 90, 80, opacity);
line(el1.x,el1.y,el2.x,el2.y);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>
最佳答案
将椭圆定义为一个对象,创建任意数量的椭圆 (15),放入数组并开始绘制,不断检测它们之间的距离。
对象自己:
var noOfEllipses = 15;
var opacity = 0;
var arrOfEllipses = [];
class Ellips {
constructor(x, y, w, h, s=2, dx=1, dy=1){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.s = s;
this.dx = dx;
this.dy = dy;
};
}
接下来,初始绘图。我给了点随机尺寸和位置,您可以添加任何单独的属性(速度/方向/颜色/等)。
function randInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function setup() {
createCanvas(windowWidth, windowHeight - 4);
for(i=0; i<noOfEllipses;i++){
var el = new Ellips(
randInt(3, windowWidth), //x
randInt(3, windowHeight), //y
randInt(3, 8), //width
randInt(3, 8), //height
randInt(10, 50)/10 //speed
);
arrOfEllipses.push(el); //put them into array
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight - 4);
}
动画。迭代点数组、位置/速度/等。是内在属性。第二个 {} 用于计算距离和绘制线条。
function draw() {
background(51, 51, 51);
fill(200, 200, 80);
noStroke();
for(var i=0; i<arrOfEllipses.length; i++){
el = arrOfEllipses[i];
el.x = el.x + el.s * el.dx;
el.y = el.y + el.s * el.dy;
if (el.x > windowWidth || el.x < 5) {
el.dx *= -1;
}
if (el.y > windowHeight || el.y < 5) {
el.dy *= -1;
}
for(var j=i+1; j<arrOfEllipses.length; j++){
el2 = arrOfEllipses[j];
if (dist(el.x,el.y,el2.x,el2.y) < 300) {
var opacity = map(dist(el.x,el.y,el2.x,el2.y),0, 300, 255, 0);
stroke(200, 200, 80, opacity);
line(el.x,el.y,el2.x,el2.y);
}
}
ellipse(el.x, el.y, el.w, el.h);
}
}
关于javascript - 如何避免重复代码导致椭圆移动?目前我必须对每个椭圆重复它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226219/