Files
sunny9898/task3/Q1b/index.js
louiscklaw 5637fbf94f update,
2025-02-01 02:07:58 +08:00

97 lines
2.3 KiB
JavaScript

let fr = 10;
let circle_xs = [];
let circle_ys = [];
let num_of_circles = 500;
let mouse_drag_start_xy = [];
let mouse_drag_end_xy = [];
let mouse_dragging = false;
let draw_rectangle = false;
function setup() {
createCanvas(400, 400);
background(220);
frameRate(fr);
// render random circle position at start
for (var i = 0; i < num_of_circles; i++) {
var circle_x = random(400);
var circle_y = random(400);
circle_xs.push(circle_x);
circle_ys.push(circle_y);
}
}
function draw() {
background(220);
// draw rectangle
// reorder 2 mouse x,y position, pick smaller one to tackle drag from bottom right to top left
rect_start = [
Math.min(mouse_drag_start_xy[0], mouse_drag_end_xy[0]),
Math.min(mouse_drag_start_xy[1], mouse_drag_end_xy[1]),
];
rect_end = [
Math.max(mouse_drag_start_xy[0], mouse_drag_end_xy[0]),
Math.max(mouse_drag_start_xy[1], mouse_drag_end_xy[1]),
];
rect_w = rect_end[0] - rect_start[0];
rect_h = rect_end[1] - rect_start[1];
if (mouse_dragging) {
noFill();
stroke("red");
rect(rect_start[0], rect_start[1], rect_w, rect_h);
}
// draw circle according to the list
fill("white");
stroke("black");
for (var i = 0; i < num_of_circles; i++) {
circle_x = circle_xs[i];
circle_y = circle_ys[i];
if (mouse_dragging) {
if (circle_x > rect_start[0] && circle_y > rect_start[1]) {
if (circle_x < rect_end[0] && circle_y < rect_end[1]) {
// circle inside rectangle, paint red
fill("red");
} else {
// circle not inside rectangle, paint white
fill("white");
}
} else {
// circle not inside rectangle, paint white
fill("white");
}
} else {
// mouse not dragging, paint white
fill("white");
}
// draw circle
circle(circle_x, circle_y, 5);
}
}
function mouseDragged() {
// console.log({ mouse_drag: [mouseX, mouseY] });
mouse_drag_end_xy = [mouseX, mouseY];
mouse_dragging = true;
// prevent default
return false;
}
function mouseReleased() {
// console.log({ mouse_release: [mouseX, mouseY] });
mouse_drag_end_xy = [mouseX, mouseY];
mouse_dragging = false;
}
function mousePressed() {
// console.log({ mouse_press: [mouseX, mouseY] });
mouse_drag_start_xy = [mouseX, mouseY];
}