如何用水平/垂直线条绘制规则几何图形 基于p5.js实现Sol LeWitt 340墙绘
你可以使用p5.js内置的clip()接口实现任意形状的线条裁剪,不需要手动叠加外层图形做遮罩,适配所有你用到的矩形、三角形、四边形等几何图形,修改逻辑如下:
- 绘制需要限定线条的图形前,先调用
push()保存当前绘图状态 - 绘制目标形状的路径(不需要额外设置填充、描边属性),调用
clip()启用该区域的裁剪规则 - 绘制你要显示在形状内部的线条,所有超出路径范围的内容会自动被隐藏
- 绘制完成后调用
pop()恢复绘图状态,避免当前裁剪规则影响后续其他图形的绘制
修改后的完整代码如下:
function setup() { createCanvas(800, 450); } function draw() { background(255); // 左上角 红色背景+椭圆裁剪蓝色横线 noStroke(); fill(255, 0, 0); rect(0, 0, 200, 200); for (let x = 50; x < 150; x += 4) { stroke(255, 255, 0); line(x, 50, x, 150) } push(); // 定义椭圆裁剪路径 ellipse(100, 100, 140, 140); clip(); strokeWeight(1); stroke(0, 0, 255); for (let i = 0; i <= 200; i += 5) { line(0, i, 200, i) } pop(); // 绘制椭圆边框 strokeWeight(40); stroke(255, 0, 0); noFill(); ellipse(100, 100, 140, 140); // 顶部中间 黄色背景+正方形裁剪蓝色竖线 noStroke(); fill(255, 255, 0); rect(250, 0, 200, 200); stroke(255, 0, 0) for (let i = 0; i <= 200; i += 4) { line(450, i, 250, i) } push(); rect(300, 50, 100, 100); clip(); for (let x = 300; x < 400; x += 3) { stroke(0, 0, 255); line(x, 150, x, 50) } pop(); // 绘制正方形边框 noFill(); stroke(255,255,0); strokeWeight(20); rect(300, 50, 100, 100); strokeWeight(1); // 顶部右侧 蓝色背景+三角形裁剪红色竖线 noStroke(); fill(0, 0, 255); rect(500, 0, 200, 200); stroke(255, 255, 0); for (let i = 0; i <= 200; i += 3) { line(700, i, 500, i) } push(); triangle(600, 50, 650, 150, 550, 150); clip(); for (let x = 550; x < 650; x += 2) { stroke(255, 0, 0); line(x, 150, x, 50) } pop(); // 绘制三角形边框 noFill(); stroke(0,0,255); strokeWeight(20); triangle(600, 50, 650, 150, 550, 150); strokeWeight(1); // 底部中间 黄色背景+梯形裁剪蓝色竖线 noStroke(); fill(255, 255, 0); rect(250, 250, 200, 200); stroke(255, 0, 0); for (let i = 250; i <= 450; i += 3) { line(450, i, 250, i) } push(); quad(255, 300, 300, 400, 400, 400, 445, 300); clip(); for (let x = 255; x < 445; x += 2) { stroke(0, 0, 255); line(x, 300, x, 400) } pop(); // 绘制梯形边框 noFill(); stroke(255,255,0); strokeWeight(20); quad(255, 300, 300, 400, 400, 400, 445, 300); strokeWeight(1); // 底部左侧 红色背景+矩形裁剪蓝色竖线 noStroke(); fill(255, 0, 0); rect(0, 250, 200, 200); stroke(255, 255, 0); for (let i = 250; i <= 450; i += 2) { line(0, i, 200, i) } push(); rect(35, 300, 130, 100); clip(); for (let x = 35; x < 166; x += 2) { stroke(0, 0, 255); line(x, 300, x, 400) } pop(); // 绘制矩形边框 noFill(); stroke(255,0,0); strokeWeight(20); rect(35, 300, 130, 100); strokeWeight(1); // 底部右侧 蓝色背景+平行四边形裁剪红色竖线 noStroke(); fill(0, 0, 255); rect(500, 250, 200, 200); stroke(255, 255, 0); for (let i = 250; i <= 450; i += 3) { line(500, i, 700, i) } push(); quad(515, 300, 620, 300, 680, 400, 570, 400); clip(); for (let x = 515; x < 680; x += 2) { stroke(255, 0, 0); line(x, 300, x, 400) } pop(); // 绘制平行四边形边框 noFill(); stroke(0,0,255); strokeWeight(20); quad(515, 300, 620, 300, 680, 400, 570, 400); strokeWeight(1); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
内容的提问来源于stack exchange,提问作者Yakob
相关产品推荐
相关产品推荐

