Skip to content

Homework Dano Wednesday

osehgol edited this page Dec 23, 2015 · 487 revisions

Guidelines

A big part of learning at ITP is learning from each other. So share your work and in exchange you'll get to see everyone else's!

  1. Do your assignment.
  2. Contribute a question.
  3. Post documentation. Something visual + your code. e.g. Blog post with code, screenshots, video. Put the URL to your post below.
  4. Post your sketch online with FTP. Put the URL to it below.
  5. (OPTIONAL FOR NOW) Place a copy of your p5.js project folder in our class' shared google drive folder.

Final Project Documentation

  • Final project presentations are Tuesday, December 1st. In class presentations will be approximately 7 minutes each, I will be strict about the time to keep everything fair. We also need 10 minutes at the end to do course evaluations.
  • Please post your final project documentation to a web page (blog post is fine) and link next to your name below. This is due Friday, December 18.
  • It's up to you to figure out how to best document your project, here are some loose guidelines if you aren't sure what to include.
    • Title
    • Brief written description
    • Visual Documentation: sketch running online, images, video, etc.
    • References: links to related projects, code samples, etc.
    • Source code (please cite your sources in the code comments)

Final Presentations Dec 2

You can reorder yourself. Please also say if we need to go on a field trip for your project.

Final Project Proposals

Final projects are a creative idea inspired by the concepts in this class. There is no requirement to use a particular aspect of programming. The idea and your enjoyment and interest in the idea is what counts. Some things to remember.

  1. Keeping things simple and small in scope is a plus. If your project idea is a big one, consider documenting the larger idea but implementing just a small piece of it.
  2. Also think about making a final project for a small audience, even one single person like a family member or friend. . . or yourself. This can be a good way to focus your idea and design process. "Generalizing" the idea can come later (or maybe not at all.)
  3. Final projects can be collaborations with anyone in any class.
  4. Final projects can be one part of a larger project integrated with Physical Computing or another class.

What you need to do now:

  1. Create a blog post documenting your idea for a final project and be prepared to present the idea in class. Your proposal should include the following (though feel free to use this as loose guidelines, you can document your idea however you see fit.)
  • Title
  • One sentence answering: "What is it?"
  • Written description of the idea.
    • How did you become interested in this idea?
    • What is the audience?
    • What questions do you have for the class (conceptual or technical)?
  • Visual material (images, videos, hand-drawn sketches etc.) that demonstrate your idea.
  • Links to any projects or references that inspired you.
  • Links to in progress sketches that demonstrates any part of the idea.
  • Questions for the class (conceptual or technical)
  1. Plan to present your idea in ~2-3 minutes leaving about 5 minutes for discussion.

Final Project Proposals

Presenting Wednesday, Nov 4

Presenting Wednesday, Nov 11

WEEK 9 VIDEO AND SOUND

Create a project making use of video or sound input or output.

Questions (example questions)

  • How do you mirror a video capture image? -- jason
    • a couple of options try x = width -x if you are doing all the pixels yourself.
  • What does it look like to work with JavaScript as a professional? If a business hires me, I'm probably not pasting their code into p5 to run tests on it... - Jordan
    • we will talk about other more fully featured (enemy of beginners) environments (text editors) like sublime next week.
  • I planned to use the cimtrackr library to create an happiness detection project but cannot figure out how to let something happen only when the happiness value is the highest. -Yan
    • I think happiness is the 4th thing that comes in with that, try this in the repeat loop to be sure
  • can you explain a 'Closure' in this class please :) - corbin
  • How can I get the average RGB values of the webcam image, without p5 crashing? =( - aaron
  if (i ==3){
      print( nfc(er[i].value, 2));
    }

Add Link Your Homework

var vid; // to hold video element
var img;

var skipPixels = 1;
var threshold = 25;


function setup() {
  
  createCanvas(640, 480);
  vid =  createCapture(VIDEO); // access webcam
  devicePixelScaling(false) ; //retinal display thing?
  vid.size(width,height);
  vid.hide(); // we will paint our own video
  img = createImage(width, height);

}

function draw() {
  background(0);
  vid.loadPixels();

  for (var y = 0; y < vid.height; y= y+ skipPixels) { 
    for (var x = 0; x < vid.width; x = x + skipPixels) { 
      //get the color of the current pixel
      var thisColor = vid.get(x,y);
      var r = thisColor[0];
      var g = thisColor[1];
      var b = thisColor[2];
      img.set(x, y, [r, g, b, 255]); //leave it the natural color
    }
  }
  img.updatePixels();
  image(img, 0, 0);

}



function keyTyped() {

  if (key == 't') {
    threshold--;
  } else if (key == 'T') {
    threshold++;
  }
  print(threshold);
}

FINDING EDGES

var vid; // to hold video element
var img;

var skipPixels = 1;
var threshold = 50;


function setup() {
  
  createCanvas(640, 480);
  vid =  createCapture(VIDEO); // access webcam
  devicePixelScaling(false) ; //retinal display thing?
  vid.size(width,height);
  vid.hide(); // we will paint our own video
  img = createImage(width, height);

}

function draw() {
  background(255);
  vid.loadPixels();
  for (var y = 0; y < vid.height; y= y+ skipPixels) { 
    //start at the second pixel so you can check against previous
    for (var x = 1; x < vid.width; x = x + skipPixels) { 
      //get color of the pixel to the left
      var previousColor = vid.get(x-1,y);
      var pr = previousColor[0];
      var pg = previousColor[1];
      var pb = previousColor[2];
      //get the color of the current pixel
      var thisColor = vid.get(x,y);
      var r = thisColor[0];
      var g = thisColor[1];
      var b = thisColor[2];

      //use pythagorean formula to find distance between this pixel and pixel to left
      var closeInColor = sqrt(pow(r - pr, 2) + pow(g - pg, 2) + pow(b - pb, 2));
      //if they are pretty different turn it black
      if (closeInColor > threshold) { 
        img.set(x, y, [0, 0, 0, 255]); //turn pixel black
     }else{
        img.set(x,y,[255,0,255,255]);
      }
    }
  }
  img.updatePixels();
  image(img, 0, 0);
 
}


function keyTyped() {

  if (key == 't') {
    threshold--;
  } else if (key == 'T') {
    threshold++;
  }
  print(threshold);
}


TRACKING (CLICK ON A PIXEL)


var vid; // to hold video element
var img;
var targetColor = [255,0,0,0];
var skipPixels = 2;
var threshold = 25;


function setup() {
  
  createCanvas(640, 480);
  vid =  createCapture(VIDEO); // access webcam
  devicePixelScaling(false) ; //retinal display thing?
  vid.size(width,height);
  vid.hide(); // we will paint our own video
  img = createImage(width, height);

}

function draw() {
  background(0);
  vid.loadPixels();
  var sumX = 0;
  var sumY = 0;
  var counter = 0;
  var targetR = targetColor[0];
  var targetG = targetColor[1];
  var targetB = targetColor[2];
  for (var y = 0; y < vid.height; y= y+ skipPixels) { 
    for (var x = 0; x < vid.width; x = x + skipPixels) { 
      //get the color of the current pixel
      var thisColor = vid.get(x,y);
      var r = thisColor[0];
      var g = thisColor[1];
      var b = thisColor[2];
      //use pythagorean formula to find distance between this pixel and color you are chasing
      var closeInColor = sqrt(pow(r - targetR, 2) + pow(g - targetG, 2) + pow(b - targetB, 2));
      if (closeInColor < threshold) {
        //sum up and count all the qualifying positions for averaging at the end
        sumX = sumX + x;
        sumY = sumY + y;
        counter++;
        img.set(x, y, [255, 0, 0, 255]); //debug turn qualifying pixesl red
      } else {
        img.set(x, y, [r, g, b, 255]); //leave it the natural color
      }
    }
  }
  img.updatePixels();
  image(img, 0, 0);
  //average all the X's and Y's that qualified.
  if (counter > 0) {
    aveX = sumX / counter;
    aveY = sumY / counter;
    fill(255, 0, 0);
    ellipse(aveX, aveY, 20, 20);
  }
}

function mousePressed() {
  //pick new color to chase
  targetColor = vid.get(mouseX, mouseY);  
  println("Target R" + targetColor[0]+ " G" + targetColor[1] + " B" + targetColor[2]);

}

function keyTyped() {

  if (key == 't') {
    threshold--;
  } else if (key == 'T') {
    threshold++;
  }
  print(threshold);
}

Week 8

SIMPLE GET TIMES DATA

function setup() {
  var url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=obama&api-key=686c52b27721b60706a1cd86dc63e395:13:22989233";
  loadJSON(url, gotData);
}

function draw() {

}

function gotData(data) {
  console.log(data)
 var theseItems = data.response.docs;
 for(var i = 0; i < theseItems.length; i++){
    print(theseItems[i].snippet);
    }
}

WITH OBJECTS

// http://developer.nytimes.com
var newsItems = [];
var nextBatch;
var previousBatch;
var batch = 1;  //the only send you 10 at a time
var queryField;
var printPageSlider;
var printPageField;

function setup() {
  createCanvas(800, 400);
  stroke(0)
  fill(127);
 
  previousBatch = createButton("Previous Batch");
  previousBatch.mousePressed(previousBatchFunction);
  nextBatch = createButton("Next Batch");
  nextBatch.mousePressed(nextBatchFunction);
  queryField = createInput("obama");
  queryField.changed(askForArticles);
  printPageSlider = createSlider(1,50,50);
  printPageField = createInput(50);
  askForArticles();
}

function askForArticles() {
  //nice to have this as a function because it is called from several places.
  //get rid of existing articles before getting more
  for (var i = 0; i < newsItems.length; i++) {
    newsItems[i].remove();
  }
  //reset print page filter
   printPageField.value( 50);
   printPageSlider.value(50 );
  //requested a key here  http://developer.nytimes.com/
  //tested queries here  http://developer.nytimes.com/io-docs
  var url = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + queryField.value() +  "&api-key=686c52b27721b60706a1cd86dc63e395:13:22989233&page=" + batch;
  loadJSON(url, createNewItemObjects);
}


function createNewItemObjects(data) {
  // console.log(data)
  //They send you an array of JSON.  For each item make a new object
  var docs = data.response.docs;
  for (var i = 0; i < docs.length; i++) {
    newsItems[i] = new NewsItem(random(width), i * 50 + 50, docs[i]);
  }
}

function draw() {
  background(255);
  printPageField.value( printPageSlider.value());  //update the field that shows the slider value
  for (var i = 0; i < newsItems.length; i++) {
    if (newsItems[i].getPrintPage() <= printPageField.value()){  //only move the ones that were closer to front page
      //the usual
      newsItems[i].move();
      newsItems[i].check();
      newsItems[i].show();
    }
  }
}

function nextBatchFunction() {
  //they send you 10 at a time so you can ask for more
  for (var i = 0; i < newsItems.length; i++) {
    newsItems[i].remove();  //get rid of old ones.
  }
  newsItems = [];
  batch++;
  askForArticles()
}

function previousBatchFunction() {
   //they send you 10 at a time so you can ask for more
  batch--;
  if (batch < 0) batch = 0;
  askForArticles()
}

//This is a constructor function that will be just like the bouncing ball with a few additions.
function NewsItem(x, y, data) {
  this.xpos = random(width);
  this.ypos = y;
  this.xdir = 1;
  this.ydir = 0;
  this.data = data;
  this.link = createA(data.web_url, data.print_page + ":" + data.snippet, '_top');
  this.link.style("width", "10000px");

  this.move = function() {
    this.xpos = this.xpos + this.xdir;
    this.ypos = this.ypos + this.ydir;
  }
  
  //pull out the page number it was printed on in the paper
  this.getPrintPage = function(){
    if (data.print_page == null) return 50;
    else return int(data.print_page);
  }

  this.check = function() {
    if (this.xpos < 0 || this.xpos > width) {
      this.xdir = -this.xdir;
    }
    if (this.ypos < 0 || this.ypos > height) {
      this.ydir = -this.ydir;
    }
  }
  this.remove = function() {
    this.link.remove();
  }

  this.show = function() {
    this.link.position(this.xpos, this.ypos);
  }

}

Start thinking about and doing some mini trial runs for a final project. They can be small sketches that form a tiny component of a larger idea. Each student will complete each assignment but only 1/2 will present each week.

  1. Create a sketch that uses an external data source. You can present in class using your laptop or put your sketch online. Here are some ideas:

    • Track personal data over the course of a few days (exercise, sleep, computer use, eating, etc.). Enter the data manually into a JSON file and visualize the results.
    • Count word frequencies in two different text sources (i.e. two different authors, two different newspapers, two different political speeches) and visualize the results.
    • Use weather data to affect elements in a sketch
    • Gather data from a google spreadsheet and use in a sketch.
  2. READ AND WATCH (optional):

APIs that might be interesting

Questions (example questions)

  • Eve - can you load a youtube video, as a callback, using the 'embed video' code form YouTube?
    • You certainly can do this in html. You can probably do this dynamically in p5 by creating a div and setting its html to the embed code from youtube. For controlling it you might need special api from youtube?
  • Eve - how can you hide the cursor and replace it with your own art. Should we do this in draw (mouseX,mouseY) style or in DOM?
  • Eve - How would you have a png sequence hold on the first frame, until a dropdown is changed, then execute the rest of the frames, then hide forever? I'm using the play library.
    • any sequence like that sounds like a job for a state machine with a variable to keep track of what state you are in, code stuck in callbacks and mouse events changing the state variable, an if statement the draw loop checking the state variable.
  • Ondina - Are there more data files than json, xml and txt that we can play with in Java Script? Is there a way to recognize fast what type of file it is? I can recognize now these 3 but not sure if there are more out there :)
    • Those are the biggies. Within the txt format there are couple list TSV (tab separated values), CSV (comma separated values). There might be a way to test the format on the fly but most of the time it is so much trouble to find the data source that you well know the format before it comes to you. The tough thing is knowing the field names or field order coming in. You can find documentation but in practice yourself using the print or console.log command to deconstruct the formatting within XML, JSON, CSV that is particular to the content.
  • Is there a way to port api data from p5 into our arduino sketches? - Jesse D
    • you bet. maybe in the callback function for your data do a serial.print Receiving stuff on the arduino is a little tougher than in p5 but very doable.
  • What are potential reasons why I keep getting an undefined value using API's? - Corbin
  • How can I get all my data into my sketch without overloading p5? - Jordan
  • How can i get data from some website such as yelp with authority and security limitations with P5 - Yan
  • Why can't I use: this.x = window.innerWidth in my own function? -Marcela

Add Link Your Homework

Week 7

  • READ AND WATCH

  • DO

    • Create a webpage that extends beyond the canvas, using p5.dom.js. You are welcome to incorporate other javascript libraries as well if you're feeling ambitious. If you're stuck for ideas, you can try going back to the graphical user interface (GUI) elements that we experimented with in week 3, and try recreating that functionality with DOM elements.

Questions (example questions)

  • Post your question here

  • Osama: Referencing DOM example 08_mouseover_mouseout, there's a img.hide() in setup() - it's also in uniHide() which gets called on mouseOut(). I notice that it's in setup() to keep the image from popping up when the play button is hit, but if I comment it out, I see the image once but on the right side of the canvas - not as defined in img.style("padding","100px"); I'm confused about it, is there a reason for that?

    • Not really sure. Somewhere in setting the visibility of the image all the elements of the page are being reflowed. If it is important, you should not rely on the browser to determine the flow of elements but instead set their absolute position with with the position property.
  • Eve: What is a callback?

    • A call back is where you arrange for your program to alert you by calling one of your functions in the future when something happens (eg user input, receive communication) .
  • Eve: What are the advantages of creating DOM elements in the p5 editor as opposed to html and css directly?

    • Kind of the same advantage of drawing in the second week vs the first week. It can be tedious to write out all the HTML for a lot of elements. Also if the elements are going to change, better to create them in code than hard code them in html.
  • When creating a button with an image, where is the triggering range for the callback located? It seemed like some of the buttons I created I had to click on the image a bit before I hit the place where the callback function would launch. -- jason

    • Once click should do it if the web page is the focus of the machine. Do you mean on non rectangular images you had to click on something that other than white?
  • I added images in html file and it worked pretty well on my local laptop. But when I uploaded everything onto cyberduck, these images don't display at all. Why and how to fix? --Yan

    • Did your upload the images into a folder in the same position relative to the html and js?
  • I heard I can insert something like mousePressed into a dom object like a slider - this sounds too good to be true? -- Corbin

    • use mouseMoved with a slider
var slider
function setup() {
  slider = createSlider(0,10,5);
  slider.mouseMoved(sliderMoved);
}
function sliderMoved(){
  print (slider.value());
}
  • I added an image on my 3D box but a 600 pixels image or 1200 pixels is very small but when I tried with a 510 pixels or 1020 pixels it fits perfectly. Is that a p5 bug?

    • don't know about that.
    1. Is there a way to reload the canvas with a new program chosen by clicking on text you defined in your CSS stylesheet? 2) Do you add hyperlinks in the CSS stylesheet, HTML file, or within the p5 environment? Jesse D
    • you can put a link to another program in the html (not css) and if they click on it, it will go there.
    • in html or p5 you can add links. the ones in p5 can be more dynamically added
  • How can I make a DOM text outside the canvas to load over and over again (like when we put a text inside the canvas? code bellow:

  var text = createP(cor1);
  text.position(360, 525);
  text.id("texto");
-- Renata
- Maybe in draw put text.value(someValue);
  • Can I creative multiple canvas on one webpage? What is the advantage of using p5.dom since there are many other javascript libraries to do beautiful buttons, sliders, etc.
  • Why can't I use: this.x = window.innerWidth in my own function?

Add Homework Here

Week 6

EXAMPLE FROM CLASS

var circles = [];

function setup() {
  createCanvas(400, 400);
  for (var i = 0; i < 10; i++){
    circles[i] = new Circle( i * 25 ,  i * 50);
  }
  fill(255,0,0);
}

function draw() {
  background(255);
  for (var i = 0; i < 10; i++){
    circles[i].move();
    circles[i].check();
    circles[i].show();
  }
}
  
function Circle(x, y){
  this.xpos = x;
  this.ypos = y;
  this.xdir = 1;
  this.ydir = 1;
  //go crazy adding more properties for the object here, color? width? speed?

  
  this.move = function(){
    this.xpos = this.xpos + this.xdir;
    this.ypos = this.ypos + this.ydir;
  }
  
  this.check = function(){
    if(this.xpos < 0 || this.xpos > width){
      this.xdir = - this.xdir;
    }
    if(this.ypos < 0 || this.ypos > height){
      this.ydir = - this.ydir;
    }
  }
  
  this.show = function(){
    ellipse(this.xpos, this.ypos, 30,30);
  }
  
}

Questions (example questions)

  • question
  • How does serial communication work b/w p5 and Arduino? How do I get readings from multiple sensors from Arduino into p5? - Jordan

ARDUINO
void loop() {  //send two things separated by a commma
  Serial.print(analogRead(A0));
  Serial.print(",");
  Serial.println(analogRead(A0));
  delay(10);
}

PROCESSING
function gotData(){
  var myData = serial.readStringUntil("\n");
  if (myData){
    var parts = myData.split(",");  //split the incoming into an array based on the comma
    input = int(parts[0]);
    input2 = int(parts[1]);
    //print(input2 + "Got data" + input);
  }
}

  • Does it matter which functions I call first? Does it make any difference? Ondina
    • sometimes yes sometimes no
  • is there anyway to manipulate color (lets say background color) when it is called in the setup function with a function that is called in the draw function? Almost like a transparent effect or something...
    • would have to see the application
  • My majority problem of this week is how to make my objects communicating with each other. So my first question is what is the basic logic of making two objects know what is the action of each other in order to react to that action. -Yan +Jess
you have to check every object against every other
for each object
   for each object
  • Can I use a function which is already defined by p5 such as mousePressed() inside of an object function? -Yan
void mousePressed(){
    for each object
      am I clicking in you
} 

  • How can we use more than one digital or analog input as part of our programs? Jesse D +Yan +Jess

    • see above
  • Is there a special way to reset object arrays? I was trying to make a restart button in my peep game but seemed to run into trouble after the restart.

    • array = [] ?
  • When I added an acceleration to the balls they eventually disappeared. Are they moving faster than the frame rate? Jess

    • don't know maybe jumping over your borders

SHOW OBJECTS

Week 5

All ICM Students will meet in the lounge on Friday at 11am-2pm

SHOW ONE BUTTON

ARDUINO
void setup() {
    Serial.begin(9600);
}

void loop() {
  Serial.println(analogRead(A0));
  delay(10);
}


PROCESSING
var serial;
var input;
var portName;

function setup() {
  createCanvas(1000,1000);
  serial = new p5.SerialPort();
  //If you don't know portName Register a list callback 
  serial.list(gotList);
  //if you do know port name just put it in this variable
  //portName= "/dev/cu.usbmodemfd1231";
  serial.open(portName);
  //Register a data callback
 serial.on('data', gotData);
}

function gotList(list){
  print(list);
  portName = list[list.length -1]; //it is often the last port in the list
  print("trying to open" + portName);
  serial.open( portName );
}

function gotData(){
  var myData = serial.readStringUntil("\n");
  if (myData){
    input = myData;
    print("Got data" + myData);
  }
}

function draw() {
  background(255)
  ellipse(input,50,20,20);
}

Week 4

  1. The idea this week is to explore re-organizing your code. It is 100% legitimate to turn in a version of a previous assignment where nothing changes for the end user, but the code has been restructured. You may, however, choose to try a new experiment from scratch. Aim to keep setup() and draw() as clean as possible, and do everything (all calculations, drawing, etc.) in functions that you create yourself. Possibilities (choose one or more):

    • Use a function to draw a complex design multiple times.
    • Use a function to draw a design in many different ways.
    • Go back to a previous p5.js sketch and try to re-create it, this time utilizing functions.
    • Invent your own exercise related to functions.
    • If you are feeling ambitious, try embedding a function into an object.
  2. READ / WATCH (Nothing required, read or watch what you find most helpful)

    • Stay tuned for a PDF link to Getting Started with p5.js
  3. Examples

Questions (example questions)

  • Is there a way to call all items in an array at once? -- jason
    • No you have to go into a repeat loop and do it. There is a slightly easier repeat loop for arrays
var person = {fname:"John", lname:"Doe", age:25}; 

var text = "";
var x;
for (x in person) {
    text += person[x];
}
  • Can I make better use of functions and objects so that my code is more economic? This, for instance, seems like something I could clean up, but the slider values are separately mapped to the pattern fills: fillRect(R); drawRect(R.slideX, R.slideY, R.slideW, R.slideH); fillRect(G); drawRect(G.slideX, G.slideY, G.slideW, G.slideH); fillRect(B); drawRect(B.slideX, B.slideY, B.slideW, B.slideH); fillRect(A); drawRect(A.slideX, A.slideY, A.slideW, A.slideH);
    • Yep using one set of code to create multiple slider object will probably help clean things up this coming week. Even just with functions your could clean up your code further by making all the commented clumps in your draw loop into functions eg //POLKA PATTERN //TRIANGLE PATTERN
  • I couldn't get preload() and loadSound() working on my code. Am I doing something wrong? Thank you. Osama
    • Not that I could see. Maybe ask Jordan or Marcela. Are you sure the file in the place it is supposed to be?
  • if making and object like a quad, am I correct in saying that you have to include syntax like 👍
    x1: -5, y1: 945, x2: 490, y2: 255, x3: 510, y3: 255, x4: 1005, y4: 945, ?
    • Yep you have specify 2 coordinates for 4 corners, 8 things.
  • How do I create unlimited size array. When I using array associated with an object, can I make this object having two different movement functions to work at the same time? -Yan
    • use the push command (or slice) to dynamically resize an array
    • not sure what you mean about two different movement functions but seems doable.
  • How do I animate 'drawing curve or bezier (in easy way)? - Marcela
    • looks like you figured something out? the trick for you looks like how to gather and store the locations.
  • How do I use mouseClicked several times? (each alternate click runs another feature)
    • maybe this is a "state machine" thing where you make a variable to keep track of which feature should be in effect and then an if statement to do different things depending on that varible?
  • How can I make a button pressed yield filter(INVERT), and change the text inside of said button? Drag the circles in my sketch; how can I avoid the circles combing into one circle once the mouse clicked falls within the diameter of both circles? - Gustavo
    • both sound like jobs for if statements. if(mouseX < bla && mouseX > bla && mouseY < ....){ filter(INVERT) and then something if (dist(mouseX, mouseY, circle1x, circle1y) > circle1.radius && dist(mouseX, mouseY, circle2x, circle2y) < circle2.radius) > circle2.radius
  • What implications does using functions have on the order of operations our programs run? -- Jesse D
    • functions happened when they are called not where they appear on the page.
    • within draw (or other functions) function calls happen in order up to down.
  • I had a hard time with putting functions inside of objects. Is there a special way to refer to variables within the same object but outside of the function where you are trying to call them? -- Jesse H
    • Hopefully "this" will be a little clearer after we talk about objects today. You should be able to use dot notation like peep.xloc or if you had an array of peeps peeps[i].xloc

Add your homework here

Week 3

  1. In general this week, you should work with rule-based animation, motion, and interaction. You can use the ideas below or invent your own assignment. Start by working in pairs as below. Can you divide an idea into two parts and combine those parts? Can you swap sketches and riff of of your partner's work? You can post together or break off and complete the assignment individually.

    • Try making a rollover, button, or slider from scratch. Compare your code to the examples on github. Later we'll look at how this compare to interface elements we'll get for free from the browser.
    • Create an algorithmic design with simple parameters. (One example is 10PRINT, example code).
    • Tie the above two together and have an interface element control the visual design or behavior of other elements in your sketch.
  2. READ / WATCH (Nothing required, read or watch what you find most helpful)

Pairs

  • Satbir - Ondina
  • Osama - Corbin
  • Yan - Jordon
  • Jess - Renata
  • Gustavo - Eve
  • Aaron - Jesse H
  • Jason - JD
  • Marcela - Ian

Questions (example questions)

  • question
  • How can I use a for loop to create variable names? - Eve
    • You can use an array variable are usually not named but numbered (you can also create a named array but you usually don't need to).
//instead of objectVar1, objectVar2, objectVar3,objectVar4..
function setup() {
  createCanvas(1000,1000);
  for(var i = 0; i < 10; i++){
    arrayOfObjects[i] = new Thing(i*10, random(height));
    //arrayOfObjects.push(new Thing(i*10, random(height)));
  }
}
  • What does rotate(); actually do? (part 2) Why does it treat functions as one object, instead of rotating each object within the function on it's own axis? -Eve
    • Rotate is rotates the whole canvas and it stays that way for the next command. This can be a little disorienting so be careful with the rotate command. Surrounding rotate with push() before and pop() after help you remember than then return to the old rotation. You are obliged to use translate to position things instead of use the x y parameters in the usual function calls.
push();  //remember
translate(100,i);
rotate(PI/6);
ellipse(0,0,10,10);
pop();  //go back to before you rotated
  • How can I make that my sketch adapt to the actual screen size of the user or maybe to the dimensions of the web browser?
    • The displayHeight displayWidth variables can do this. createCanvas(displayWidth, displayHeight);
  • How on earth can I make a triangular-shaped button? Or a button around any object, for that matter? ALSO, what's the deal with mobile optimization? Why do my sketches not respond to touch on my phone like they do to mouseX/Y on desktop? - Jordan
    • You can use the get command to learn the color under the mouse and have very particular color buttons. Not sure about the mobile thing.
  • How can I consider the object coordinates the reference itself do some transformations such as movement and rotation, instead of considering the coordinates from the canvas? - Renata
    • Might need more info but suspect answer is objects.
  • Is there a better way to use random() or other functions to return numbers that are not so concentrated in certain range? -Yan
    • Might need more info but you can look into things like Perlin Noise
  • How can I make a button reveal other objects randomly yet are in motion when they are produced? - corbin
    • Might need more info but suspect answer is objects.
  • My question might be similar to Renatas: is there a way to make items drawn with for loops individually addressable so that they could be used in if statements, or do they have to be written out in a bunch of if statements? -- jason
    • Might need more info but suspect answer is objects.
  • Is there a way to separate what a button/rollover does from what other parts of code does? For me, my button affected my random circles, making fewer circles that moved faster. -Satbir
    • Keeping things inside and outside if statements.
  • How can we change the color mode to either additive or subtractive color mixing (and not simply mixing by varying opacity)? - Gustavo
    • Look into blend options. Not sure they are part of p5 yet.
  • How do we make shapes, objects triggered by a mouseover go away when you move away from the mouseover area -- Jesse D
  • How can you properly call this function. It doesn't seem to update all objects. -Eve
function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

Homework Links

Week 2

  1. Create a sketch that includes (all of these):
  • One element controlled by the mouse.
  • One element that changes over time, independently of the mouse.
  • One element that is different every time you run the sketch.
  1. Start looking for computational that interests you. Add links below. *ooh la la
  1. READ AND WATCH:

Questions (example questions)

  • Why can't we declare the variable values when we initialize it? -- Renata
    • You usually can. Sometimes you learn more in setup (eg width, height) and want to initialize separately there
  • How can I access information (such as weather) from websites? -- Aaron
    • Jump ahead to the data week. Look at LoadString, LoadXML, LoadJSON
  • Are there math operators that consume more memory or slower than others? -- Jason
    • For now don't worry about optimization. Eventually you might worry about graphics but never math. This code will output the number of times your computer can do math in one second, and the number of times it can do graphics. Graphics is a lot less but still much more than you need.
        function setup() {
          var counter = 0;
          var startTime = millis();
          while(millis() < startTime + 1000){
             counter = counter + 1;
          }
          print("Math: " + counter);

         counter = 1.0;
         startTime = millis();
         while(millis() < startTime + 1000){
            ellipse(10,10,100,100);
            counter = counter + 1.0;
         }
         print("With Graphics: " + counter);
        }
  • Why can't I call up an image in P5 using its URL? Can I set a moving point as a variable? - Jordan
    • The big bummer of javascript is some called "cross domain" restrictions that don't allow you to use stuff from other websites. There are work around but for now use a local file.
    • Maybe think of it as variable moving and point using that variable?
  • What methods should we employ in order to best organize our code - Jesse D +1 Jess
    • Use the "Reformat" in the "View" menu to clean up indentation
    • **Call your variables that will make your code more readable like ellipse(horizEyeLoc,vertEyeLoc,eyeWidth,eyeWidth); **
    • Be excessive with comments
    • Use functions and objects (coming soon)
  • If I add a mousePressed() function to my drawing program are all the previous shapes I drew still in memory behind the new background or have they been forgotten? -Jess
    • Yep. When you draw a pixel on top of another pixel it is forgotten. You would would have to manually store the old value in a variable.
  • How to setup multiple framerates for different animations. And how to make things keep on happening even the mouse has been released? How to arranage elements in order(one is on top and the other is below)-Yan
//frameRate and delay are not great commands better to learn to use timers with the millis() function**. 
var lastTime = 0;
var xLocation = 50
function setup() {
  createCanvas(1000,1000);`
}

function draw() {
  if(millis()-lastTime > 1000){
    xLocation = xLocation + 10;
    lastTime = millis(); //remember to reset the timer
  }
  ellipse(xLocation, 50, 30,30)
}
  • Set a variable in mousePressed that gets used in draw instead of using drawing commands in mousePRessed

  • lines of code above others will draw things on further back layers.

  • How can I make objects rotate, imagine what a ninja star would look like floating through the air - Corbin

    • use rotate function but be careful to surround it with pushMatrix() before and popMatrix() after.
  • How can I set color to be random, yet within defined bounds/ranges/values of RGB values? Essentially, I am trying to get rid of greys, but don't necessarily want to only use 255 values for RGB (for example, in order to make yellow, blue's value needs to be at zero). - Gustavo

    • **Maybe red = random(0,255); green = random(0,255); blue = random(0,7); **

Code from in-class examples

Combining two design patterns (genre of recipes)

State machine has a "mode" variable that keeps track of which stage or level you are on at in a sequence. The if statement does different things in the draw loop depending on which stage. They you need something like a mouse click, score or in this case timer to change the mode or stage your are in.

Timer allows do things at different rates than the draw loop goes. You need a variable to keep track of lasttime you did something, an if statement that checks whether there difference between the stored time and the current millis is enough to do the the thing again, and then reset the variable to the current millis to check against in the future.

 var lastTime = 0; 
 var mode = 0;
  
 function setup() { 
   createCanvas(1000,1000);
   
 }
 function draw() { 
   if(millis()-lastTime > 1000){ 
     mode = mode + 1;
     lastTime = millis(); //remember to reset the timer 
     } 
   if (mode == 0){
     print("Mode "+ mode);
   }else if (mode == 1){
     print("Mode "+ mode);
   }else if (mode == 2){
      print("Mode "+ mode);
   }else if (mode == 3){
      print("Mode "+ mode);
   }
 }

Using having a separate variable for speed and direction and using a compound if statement

var directionX = -1;
Var speed = 1;

function setup() {
  createCanvas(1001,1001)
  circleX = width;
}

function draw() {
  background(255);
  ellipse(circleX, 50, 20 ,20);
  circleX = circleX + directionX* speed;
  if (circleX < 0  || circleX > width){
    directionX = -directionX;
    speed = speed + 10;
  }

}

Using a for loop to make a moving catapillar

var catX = 20;
var catY = 20;

function setup() {
  createCanvas(1000,1000);
 }

 function draw() {
   background(1000,1000);
   catX = catX + 1;

   for (var i = 0; i < 8; i = i + 1) {
     ellipse(catX + i * 5, catY + i * 5, 20, 20);
   }
 }

Pairs

Arrange to spend a half hour working side by side. You can do separate projects or continue on together with a single project.

  • Jordan and Jess SD
  • Jason and Renata
  • Marcela and Yan
  • Gustavo and Osama
  • Ondina and Jesse D
  • Eve and Satbir
  • Aaron and Corbin and Jesse H

Homework Links

Section 2 (12:10pm to 2:40pm)

Week 1

  • SET UP:

    • Download the p5.js editor
    • Sign up for the ITP ICM Google Group
    • Send an email subject line "HI" so I can grab your preferred email address for a cc list. Please also tell me if I am mispronouncing your name and I will come to your office hours to get it right.
    • Sign up for a Github Account. You need it to edit this wiki page.
  • DO:

    • Create your own screen drawing: self-portrait, alien, monster, etc. Use only 2D primitive shapes – arc(), curve(), ellipse(), line(), point(), quad(), rect(), triangle() – and basic color functions – background(), colorMode(), fill(), noFill(), noStroke(), stroke(). Remember to use size() to specify the dimensions of your window.
  • READ / WATCH (if helpful):

    Added

  • ASK QUESTIONS: Contribute at least 1 question below. (Name optional.)

Questions | Examples

  • question Why does it not work if I say circle? *At one point, P5 stopped generating any changes or new code I added to my project. What's the deal with that? I copied and pasted the code into a new project and it worked fine after that. - Jordan

  • Is there a better way to anticipate the bend of a curve? -- jason

  • how can we set specific settings (color, coordinates, stroke weight etc) without having to repeat it for each shape? -- renata

  • Does anyone have a simple way of understanding drawing arcs? Specifically determining the radians start and stop parameters. -- Gustavo

  • Why shapes created by bezier cannot be colored if it is noStroked, but shapes created by quadraticVertex can be colored even though it is noStroked? --Yan

  • What is the difference between function setup() and function draw(), What do I put under them? If the element is static without interaction(for example, background image), is it necessary to put it under function draw()? --Yan

  • Is there a better way to draw organic shapes without so many parameters?(using math?)--Yan (+1 - Jess)

  • What is the determinant of the minimum time of refresh of the drawing? Is it the server? Is it the browser? Is it internet speed? --Aaron

  • I used the ellipseMode(CENTER) for the head and when I tried to do the mouth with an arc() function, it wasn't centered like the head. I'm not sure why. Anyone knows why? - Ondina

  • What are the differences between some of the different coding environments we will use such as the p5.js text editor, sublime text, xcode. Is there something happening behind the scenes of each editor which makes one suited for specific applications? - Jesse D

  • Is there a way to add repetitive shapes without reentering the same line over and over and over again? - Satbir

  • Can I setup the position of an object relating to already existing object? - Marcela

  • How do I make multi-line comment? - Marcela

  • Is there a way to duplicate a drawing while moving it along the x or y axis? I was trying to figure out how to do it without rewriting the whole project with new coordinates. - Jesse H

*is there an easy way to understand where objects start and stop? for example, what is considered the 1st,2nd,3rd,4th corner of a rectangle? Corbin

  • How can i import svgs? -Eve

*How can I see the

Add Your Homework