这是图片:
我正在使用 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);
}
最佳答案
要实现您想要的效果,您必须更改设置。您必须重新绘制每一帧中的所有点。
每帧创建一个点并将该点存储到数组中:
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>
关于javascript - 使用 p5.js 在图像上摆动形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61586148/