【p5.js实战】我的自画像

mac2026-02-18  12

配着理工男黑框眼镜的我顶着闪耀的秃头;作为一名合格的数媒学子,几乎每天都要爆肝作业到深夜(包括此刻),直至头脑发昏、眼冒金星。

画这个自画像基本就是图形拼凑的过程,首先是画出自己的头型,然后根据头的比例逐渐找到各个部位的位置,绘制相应的图形,再稍微调整一下大小,整个自画像基本就成型了。

接着要实现秃头上固定位置的旋转星星以及围绕秃头依次散开的星星(动态)。

定义angle存储每个凸顶点的间隔角度:两倍的π / 顶点数(顶点数应作为参数被传入)定义halfAngle存储每个凹顶点与相邻凸顶点的间隔角度:angle / 2使用beginShape和endShape绘制每个星星:使用 beginShape() 及 endShape() 函数可创造更复杂的形状。beginShape() 将开始记录形状的顶点,而 endShape() 则停止记录。所提供的参数将决定由所提供的顶点该画出怎样的形状。如果模式没有被提供,所定义的形状可以是任何不规则的多边形。 可提供给 beginShape() 的参数包括 POINTS、LINES、TRIANGLES、TRIANGLE_FAN、TRIANGLE_STRIP、QUADS 及 QUAD_STRIP。在调用 beginShape() 函数之后,一系列 vertex() 函数必须接着调用。调用 endShape() 以停止绘制形状。每个形状都将会有由当时外线色所定义的外线色及当时的填充色。 变形函数如 translate()、rotate() 及 scale() 在 beginShape() 内不会有任何效果。其他形状如 ellipse() 或 rect() 也不能在beginShape()里面使用。通过计算式 x = rx + cos(A) * r2; y = ry + sin(A) * r2; 计算出圆周上各等分点的坐标,rx与ry不相等并不影响最终形状endShape(ClLOSE)闭合各个顶点。

 

下面是自画像代码:

function setup() { createCanvas(320, 320); } function draw() { background("#FA8072"); push(); translate(width * 0.5, height * 0.5); fill("#f8ff6e") noStroke(); for(let i = 60; i <=100; i+=5) { oneStar(i); } pop(); name(); face(); glasses(); nose(); mouth(); push(); translate(width * 0.6, height * 0.28); rotate(frameCount / -100.0); stroke("#FFFFE0"); fill("#fc722d") star(0, 0, 10, 25, 4); pop(); } function name() { // 名字 push(); stroke("#DC143C"); strokeWeight(5); noFill(); rectMode(CENTER); rect(85, 43, 30, 35, 5); line(90, 55, 105, 65); line(218, 30,208, 60); line(218,30,228,60); line(228, 60, 238, 30); line(238, 30, 248, 60); pop(); } function face() { // 脸 push(); noStroke(); ellipseMode(CENTER); fill("#FFDEAD"); ellipse(160, 160, 150, 180); fill("#FF7F50"); ellipse(120,205,25,20); ellipse(200,205,25,20); pop(); } function cap() { // 帽子 push(); noStroke(); fill(100, 125, 128); ellipse(160, 110, 140, 60); fill("#008080"); rectMode(CENTER); rect(160, 85, 85, 60, 5); pop(); } function glasses() { // 眼镜 push(); rectMode(CENTER); fill("#F0FFFF"); strokeWeight(3) rect(135, 170, 40, 25); rect(185, 170, 40, 25); line(155, 170, 165, 170); pop(); } function nose() { // 鼻子 push(); stroke("#F4A460"); fill("#F4A460"); triangle(160, 190, 155, 202, 165, 202); pop(); } function mouth() { //嘴巴 push(); stroke("#A52A2A"); fill("#A52A2A"); arc(159, 218, 30, 25, 0, 3 + QUARTER_PI, CHORD); pop(); } function star(x, y, radius1, radius2, npoints) { let angle = TWO_PI / npoints; // 两倍的PI,圆形周长与直径的比例的两倍 let halfAngle = angle / 2.0; beginShape(); for (let a = 0; a < TWO_PI; a += angle) { let sx = x + cos(a) * radius2; let sy = y + sin(a) * radius2; vertex(sx, sy); sx = x + cos(a + halfAngle) * radius1; sy = y + sin(a + halfAngle) * radius1; vertex(sx, sy); } endShape(CLOSE); } function oneStar(frameee) { push(); rotate(frameCount / -frameee); star(120, 0, 11, 25, 5); pop(); }

 

最新回复(0)