Error when using an If statement in draw

I'm trying to compare colours from two images - one red and one blue. Here's the code that I keep getting an error with (basically loading a RED.jpg and checking to see if the pixel (1,1) is red and if it is displaying a blue ellipse (just as a test). The If line provides me with an error as follows:

The error: 23: Uncaught SyntaxError: Unexpected identifier "%cDid you just try to use p5.js's exp() function? If so, you may want to move it into your sketch's setup() function.\n\nFor more details, see:"

Not clear why I get this error as Daniel Shiffman uses an If statement within his videos and it works fine there.

var pix, RED;
var imgBLUE, imgRED;

function preload() {
  imgRED = loadImage("RED.jpg");
  imgBLUE = loadImage("BLUE.jpg");

function setup() {
  createCanvas(920, 400);
//  background(165);
  RED = 'rgb(255,0,0)';

function draw() {
background (0);
pix = imgRED.get(1,1);

If (pix == RED)  {
ellipse (100,100,100,100);

(I have this process working very well in Processing as an alternative - was looking forward to using P5.js for this).

As always any help is gratefully appreciated. Many thanks.


  • Answer ✓

    couldn't work out how to do the paste with code line numbers from the editor

    highlight code, press ctrl-o

  • @koogs - thanks for your help on the presentation of the code. Looks better now.

  • edited April 2016 Answer ✓

    p5.Image::get() method w/ 2 parameters returns an Array:

    Therefore you can't compare it w/ a String like 'rgb(255,0,0)'.

    Instead use function color passing your 'rgb(255,0,0)' in order to get a p5.Color object from it:

    p5.Color got a property named rgba which is an Array w/ 4 values just like what method get() returns.

    You can compare them this way: *-:)

    function rgbEquals(rgb1, rgb2) {
      "use strict"
      const len = rgb1.length - 1
      for (let c = 0; c < len; ++c)  if (rgb1[c] !== rgb2[c])  return false
      return true
    rgbEquals(imgRED.get(1,1), [255, 0, 0])
  • edited April 2016

    @GoToLoop thanks so much for your help. Makes sense now you mention it - just couldn't get it to work. I really appreciate your links and code. Will try this out. Thanks again.

Sign In or Register to comment.