[聚合文章] p5.js作品集(1):樱花

JavaScript 2017-12-19 16 阅读
草图.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

p5.js在线编辑器界面.png

注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。