这是图片:
我正在使用p5.js在图像上绘制随机圆。我下面有使圆环出现的代码,我想要。但是,我也希望所有点都可以摆动。我在弄清楚这方面时遇到了麻烦。我感谢任何提示!谢谢
let img;
let smallPoint, largePoint;
let fr = 30;
function preload() {
img = loadImage('images/face.png');
}
function setup() {
createCanvas(720, 800);
let cvn = createCanvas(1000, 1000);
let x = (windowWidth - width) / 2;
let y = (windowHeight - height) / 2;
cvn.position(x,y);
smallPoint = 5;
largePoint = 20;
noStroke();
background(255);
image(img, 0, 0, 720, 800);
img.loadPixels();
frameRate(fr);
}
function draw() {
let pointillize = map(mouseX, 0, width, smallPoint, largePoint);
let x = floor(random(img.width));
let y = floor(random(img.height));
let pix = img.get(x, y);
fill(pix);
ellipse(x, y, pointillize, pointillize);
}
答案 0 :(得分:1)
要实现所需的功能,必须更改设置。您必须重新绘制每一帧中的所有点。
每帧创建一个点并将该点存储到数组中
points = []
function draw() {
let pointillize = map(mouseX, 0, width, smallPoint, largePoint);
let x = random(img.width);
let y = random(img.height);
let pix = img.get(x, y);
points.push( {x: x, y: y, color: pix, size: pointillize});
// [...]
在每帧中绘制图像并在其顶部绘制所有点:
// [...]
for(let i= 0; i < points.length; i++ ) {
let p = points[i];
fill(p.color);
ellipse(p.x, p.y, p.size, p.size);
}
}
要实现“摆动”效果,建议使用sin()
函数,计算偏移量,并使用millis()
随时间更改偏移量。
为每个点创建一个随机比例(sx
,sy
)和偏移量(dx
,dx
)
let dx = random();
let dy = random();
let sx = random();
let sy = random();
points.push( {x: x, y: y, color: pix, size: pointillize, dx: dx, dy: dy, sx: sx, sy: sy});
计算取决于时间(t
)的摆动效果。在下面的摆动取决于十分之一秒(millis() * 0.01
),其数量是从-3到3:
let t = millis() * 0.01;
let x = p.x + sin(PI * p.dx + t * p.sx) * 3;
let y = p.y + sin(PI * p.dy + t * p.sy) * 3;
ellipse(x, y, p.size, p.size);
查看示例:
let img;
let smallPoint, largePoint;
let fr = 100;
function preload() {
img = loadImage('https://raw.githubusercontent.com/Rabbid76/graphics-snippets/master/resource/texture/parrot_image.jpg');
}
function setup() {
let cvn = createCanvas(img.width, img.height);
let x = (windowWidth - width) / 2;
let y = (windowHeight - height) / 2;
cvn.position(x,y);
smallPoint = 5;
largePoint = 20;
img.loadPixels();
frameRate(fr);
}
points = []
function draw() {
let pointillize = map(mouseX, 0, width, smallPoint, largePoint);
let x = random(img.width), y = random(img.height);
let pix = img.get(x, y);
let dx = random(), dy = random(), sx = random(), sy = random();
points.push( {x: x, y: y, color: pix, size: pointillize, dx: dx, dy: dy, sx: sx, sy: sy});
noStroke();
background(255);
image(img, 0, 0, img.width, img.height);
let t = millis() * 0.01;
for(let i= 0; i < points.length; i++ ) {
let p = points[i];
fill(p.color);
let x = p.x + sin(PI * p.dx + t * p.sx) * 3;
let y = p.y + sin(PI * p.dy + t * p.sy) * 3;
ellipse(x, y, p.size, p.size);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>