int frames = 20;
int framesToSave = 0;
// 设置当前有20个图层
PGraphics pg[] = new PGraphics[frames];
void setup() {
size(500, 500);
prepareGraphics();
}
void draw() {
int currFrame = frameCount % frames; // 0 .. 19
if (mousePressed) {
pg[currFrame].beginDraw();
pg[currFrame].line(mouseX, mouseY, pmouseX, pmouseY);
pg[currFrame].endDraw();
}
// 显示当前图层
image(pg[currFrame], 0, 0);
if (framesToSave > 0) {
// 保存 gif 文件
saveFrame("loop####.gif");
framesToSave--;
}
}
void keyPressed() {
if (key == 's') {
framesToSave = frames;
}
if (key == ' ') {
prepareGraphics();
}
}
// 按空格键重置画板
void prepareGraphics() {
// 初始化创建20个图层
for (int i=0; i<frames; i++) {
pg[i] = createGraphics(width, height);
pg[i].beginDraw();
pg[i].background(0);
pg[i].stroke(255);
pg[i].strokeWeight(3);
pg[i].endDraw();
}
}
效果图如下:

本文介绍使用Processing编程环境创建动态GIF的方法。通过20个图层的循环绘制和鼠标交互,实现线的连续绘制效果,并能保存为GIF文件。文章详细展示了如何初始化图层、响应鼠标事件及键盘事件,以及如何保存动画为GIF。
974

被折叠的 条评论
为什么被折叠?



