Interaction Design WikiProgramming

p5.js SVG + Images

Canvas 2D Renderer

p5.js uses Canvas 2D Renderer to display images as bitmaps. It uses an image(img, x, y) function, where img is the source image and (x, y) is the position of the image. Two more parameters can optionally be added to specify the width and height of the image.

let img; // Declare variable 

function setup() {
  createCanvas(720, 400);
  img = loadImage('pathToYourImage/imageName'); // Load the image
}

function draw() {
  // Displays the image at its actual size at point (0,0)
  image(img, 0, 0);
  // Displays the image at point (0, height/2) at half size
  image(img, 0, height / 2, img.width / 2, img.height / 2);
}

In this example a one-dimensional array is used to display multiple images. To access an element of this array, we use these '[index]' brackets.

var imageList = [];

function preload() {
  imageList[0] = loadImage('1.png');
  imageList[1] = loadImage('2.png');
  imageList[2] = loadImage('3.png'); 
}

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

function draw()
{
  background(255);
  translate(10,100);
  for(var i=0; i < imageList.length; i++)
    {
  image(imageList[i],0,0,imageList[i].width/2,imageList[i].height/2); 
       translate(150,0);
    } 

}


SVG Renderer

Instead of using pixel-baed Canvas 2D Renderer, it is also possible to use SVG Renderer, which is is based on SVG Document Object Model. The performance of SVG Renderer might be lesser, but it allows to render SVG-format vector images in any size without loss of quality. In p5.js you will need to use external library to make use of this feature. Here you can find more references about how to use the available methods.

When exporting SVGs from Illustrator, the following settings should produce working results. This does, however, depend on your version of Illustrator. 


var ZHDK,NASA;
var rotAngle = 0.0;

function preload() {
    ZHDK = loadSVG('zhdk.svg');
    NASA = loadSVG('nasa.svg');
    frameRate(20);
    
}

function setup() {
  createCanvas(600, 200, SVG);
  imageMode(CENTER);
}

function draw() {
  background(255);
    
  translate(width *0.5, height *0.5);
  rotate(rotAngle);
  image(ZHDK, 0, 0, ZHDK.width, ZHDK.height);  
  rotAngle+= 0.01;
  let scaleFactor =dist(mouseX, mouseY, width/2, height/2);
  scaleFactor = map(scaleFactor, 0, width, 1, 4);
  translate(mouseX, mouseY);
  scale(scaleFactor);
  image(NASA, 0, 0, NASA.width, NASA.height);

}

Exercise

Exercise 9 possible solution