![](https://img.haomeiwen.com/i9469540/4cb06843151df735.png)
作品链接
https://codepen.io/SampleTape/full/Rxbrde/
主要方法
- rect()
- rotate()
- translate()
草图
![](https://img.haomeiwen.com/i9469540/1fc3ef69118279bc.png)
过程分解
初始化:新建一块画板
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);//设置背景颜色
}
一、画一个矩形
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw(){
rect(0,-40,160,80);//画一个矩形
}
二、画一个无边框粉色矩形
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw(){
noStroke();//无边框
fill(255, 20, 147);//粉色
rect(0,-40,160,80);//画一个矩形
}
三、将坐标轴平移至窗口中心
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw(){
translate(windowWidth / 2, windowHeight / 2);//将坐标轴平移至窗口中心
noStroke();//无边框
fill(255, 20, 147);//粉色
rect(0,-40,160,80);//画一个矩形
}
四、以原点为轴心将坐标轴旋转后继续绘制矩形
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw(){
translate(windowWidth / 2, windowHeight / 2);//将坐标轴平移至窗口中心
noStroke();//无边框
fill(255, 20, 147);//粉色
rect(0,-40,160,80);//画一个矩形
//注意:
//矩形左边中点应与坐标轴原点重合
//矩形的y参数上移矩形高的一半
rotate(PI * 2 / 5);//将坐标轴旋转72deg
rect(0,-40,160,80);//画第二个矩形
rotate(PI * 2 / 5);//将坐标轴旋转72deg
rect(0,-40,160,80);//画第三个矩形
rotate(PI * 2 / 5);//将坐标轴旋转72deg
rect(0,-40,160,80);//画第四个矩形
rotate(PI * 2 / 5);//将坐标轴旋转72deg
rect(0,-40,160,80);//画第五个矩形
}
五、将绘制5个矩形的操作简化到for循环中(完整代码)
function setup(){
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw(){
translate(windowWidth / 2, windowHeight / 2);//将坐标轴平移至窗口中心
noStroke();//无边框
fill(255, 20, 147);//粉色
for(var i = 0; i < 5 ; i++){
rect(0,-40,160,80);//画一个矩形
rotate(PI * 2 / 5);//将坐标轴旋转72deg
}
}
本文代码均可在p5.js的在线编辑器运行
http://alpha.editor.p5js.org
![](https://img.haomeiwen.com/i9469540/2eb5e983dc026261.png)
网友评论