01 Graphic Basics¶
1 My AI robot¶
Draw your first AI robot with P5js. You can use line, ellipse, rectangle and text.
AI robot¶
First draw your robot on the white borad, then translate it into code.
Here are some drawings:
Robot code example:
let i = 0;
function setup() {
createCanvas(320, 350);
frameRate(4);
}
function draw() {
background(220);
fill(249,194,163);
//head
circle(150, 100, 100);
//foot
circle(125, 240, 50);
circle(175, 240, 50);
//body
fill(96,151,235);
rect(100, 100, 100, 140);
//legs
line(100, 120, 50 + i % 2 * 10, 160);
line(200, 120, 240 - i % 2 * 10, 160);
//hand
fill(249,194,163);
circle(50 + i % 2 * 10, 160, 20);
circle(240 - i % 2 * 10, 160, 20);
//“S”uper
fill('yellow');
quad(100, 120, 200, 120, 152, 160, 148, 160);
fill('red');
textSize(30);
text('S', 140, 145);
fill(255);
i++;
}
Steps¶
Follow the steps to finish your robot:
- (10min) Draw robot on paper.
- (10min) Draw robot with white borad.
- (60min) Code your robot!
You can find very helpfule API information on reference page. Also below are some code examples you might use:
//shape
line(30, 20, 85, 75);
circle(30, 30, 20);
ellipse(56, 46, 55, 55);
stroke(255,255,255);
strokeWeight(3);
fill(255,255,0);
noFill();
Examples¶
1 Robot NIU¶
2 By Student Scean¶
3 By Student Max¶
4 By Student York¶
Discuss and explore in-depth¶
- Read the code written by your partner. Explain the code to erveryone.
- How to write comments when coding?
- Find the function that you have missed,then upgrade your code with those missing functions.
2 Mouse Events: click and drag¶
We use mousePressed function to process the logic when use click mouse. And mouseDragged function is for dragging a mouse.
function setup() {
createCanvas(600, 600);
noLoop();
}
function draw() {
background(220);
}
let snapx;
let snapy;
function mousePressed() {
snapx = mouseX;
snapy = mouseY;
}
function mouseDragged() {
let r = sqrt((mouseX-snapx)*(mouseX-snapx) +
(mouseY-snapy)*(mouseY-snapy))
fill(random(255),random(255), random(255), random(100,255));
ellipse(snapx, snapy, r, r);
return false;
}
You can play the code here
Drag the mouse to create an picutre like this:
Use what you have learned today and change the code to make it different.
3 Weave line¶
Try the code below and adjust the parameter value for frameRate()
, understand how it works like weaving.
let i = 0;
function setup() {
createCanvas(400, 400);
background(127);
frameRate(60);
}
function draw() {
noStroke();
fill(129, 206, 15);
rect(0, i, width, 10);
fill(255);
rect(i, 0, 10, height);
i += 20;
}