Reputation: 11
I am currently working on a project where the user is able to draw a rectangle based on the mouse's position. I have this so far but the problem is that once the mouse is released, the rectangle disappears. I think I need to use mouseReleased
but I'm not sure exactly what to put in it.
Here's my code so far:
var x;
var y;
var x2;
var y2;
function setup() {
createCanvas(400, 400);
}
function draw() {
x2 = mouseX;
y2 = mouseY;
background(255);
if (mouseIsPressed) {
rectMode(CORNERS);
rect(x, y, x2, y2);
}
}
function mousePressed() {
x = mouseX;
y = mouseY;
}
function mouseReleased() {
}
Upvotes: 0
Views: 447
Reputation: 210908
Create a list to store the drawn rectangles:
var rectangles = []
Add the rectangle to a list when the mouse is released:
function mouseReleased() {
rectangles.push({x: x, y: y, x2: x2, y2: y2})
}
Draw all the rectangles in the list in every frame:
for (let i=0; i < rectangles.length; ++i) {
let r = rectangles[i]
rect(r.x, r.y, r.x2, r.y2)
}
var x, y, x2, y2;
var rectangles = []
function setup() {
createCanvas(400, 400);
rectMode(CORNERS);
}
function draw() {
x2 = mouseX;
y2 = mouseY;
background(255);
noFill()
if (mouseIsPressed) {
rect(x, y, x2, y2);
}
for (let i=0; i < rectangles.length; ++i) {
let r = rectangles[i]
rect(r.x, r.y, r.x2, r.y2)
}
}
function mousePressed() {
x = mouseX;
y = mouseY;
}
function mouseReleased() {
rectangles.push({x: x, y: y, x2: x2, y2: y2})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>
Upvotes: 1