01 Graphic Basics

1 My AI robot

Draw your first AI robot with P5js. You can use line, ellipse, rectangle and text.

Draw your robot on the white borad first, 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);
  circle(150, 100, 100);
  circle(125, 240, 50);
  circle(175, 240, 50);
  fill(96,151,235);
  rect(100, 100, 100, 140);
  fill(255);
  line(100, 120, 50 + i % 2 * 10, 160);
  line(200, 120, 240 - i % 2 * 10, 160);
  fill(249,194,163);
  circle(50 + i % 2 * 10, 160, 20);
  circle(240 - i % 2 * 10, 160, 20);
  fill('yellow');
  quad(100, 120, 200, 120, 152, 160, 148, 160);
  fill('red');
  textSize(30);
  text('S', 140, 145);
  fill(255);

  i++;
}

P5Editor

3 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: