0

Given an image I upload it's copy at a p5.js canvas. After 2 clicks I record coordinates and I wanna draw a rectangle with this coordinates. However, I cannot find a proper way to do so and draw rectangle at a very wrong place. There is the code https://jsfiddle.net/7gvuqtoj/

//p5 for a rect
  function preload(){
    img = loadImage('cat.jpg');
  }

  function setup() {

  var canvas = createCanvas(img.width, img.height);
  translate(0,0);
  // Move the canvas so it’s inside our <div id="sketch-holder">.
  // canvas.parent('img');
  background(255, 0, 200);
}

function draw(){
  image(img,0,0);
  rect(koors[0],koors[1],koors[2],koors[3]);
}

Might also have a look at: http://abereznyak.ru/projects/vue/ - working cat example

Bereznyak
  • 75
  • 1
  • 13
  • I'm not entirely sure I understand what you're trying to do, when I click Load Image on the jsfiddle example, nothing happens. And when I click twice on the image of the working example I don't retrieve any coordinates? – Luke Garrigan Jan 13 '19 at 16:14

1 Answers1

1

The rect function in p5.js takes x, y, height and width by default.

The default mode is rectMode(CORNER), which interprets the first two parameters of rect() as the upper-left corner of the shape, while the third and fourth parameters are its width and height. See

You can calculate the height and width of the rectangle by finding the difference between x values and the difference between y values.

Here is a code example.

function setup(){
  createCanvas(300,300);
  stroke(0);
}
var x1,x2, y1,y2;
x1 = -1;
function draw(){
    if (x1 > 0 && x2 > 0){
        if (x1 > x2){
            let t = x1;
            x1 = x2;
            x2 = t;
        }
        if (y1 > y2){
            let t = y1;
            y1 = y2;
            y2 = t;
        }
        rect(x1, y1, x2-x1, y2-y1);
        x1=x2=y1=y2=-1;
    }
}
function mouseClicked(){
  if (x1 < 0){
    x1 = mouseX;
    y1 = mouseY;
  } else {
    x2 = mouseX;
    y2 = mouseY;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
Charlie Wallace
  • 1,810
  • 1
  • 15
  • 17
  • Wow Charlie, thanks about your snipped at https://stackoverflow.com/questions/47224668/p5-set-fill-color-using-hex-string-and-alpha/54391833#54391833 – dani herrera Feb 21 '19 at 07:28