We are about to switch to a new forum software. Until then we have removed the registration on this forum.
function setup( )
{
createCanvas(1366, 700)
background(0)
}
function draw ( )
{
fill('green')
rect ( 100,100,300,300 )
}
function mouseClicked()
{
background(255)
}
How to change the background color by clicking only on the square ?
Answers
https://p5js.org/reference/#/p5/mouseX
http://JeffreyThompson.org/collision-detection/point-rect.php
My question you have read ? On the website are examples of events for the entire screen, and I need an event for a particular element !
There is an example in the link above how to check your point (mouseX,mouseY) against your rectangle
Replace px and py with mouseX and mouseY and rx... with your rectangle
A rect() isn't an element! It simply instructs pixels to be drawn on the canvas element as a rectangular shape. :-@
Thank you, I understand. But for me, it's bad news that P5.js you cannot bind an event handler to geometric forms. The program code increases, and in General, this approach is generally not practiced. Tell me, do you have specialists who could tweak the code of the framework to allow event binding ?
On the forum there are freelancers ? Want to hire a person to hang an event handler on geometric shapes.
Given p5.js is a JS library, we can at least have an HTMLButtonElement via createButton():
It's rectangular shape only though. And its position() isn't bound to p5.js' HTMLCanvasElement created via createCanvas():
For other geometric shapes, you're gonna need to create a
class
to store their coordinate & dimension pairs: https://Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructorBe aware that p5.js, being a spinoff of Processing Java, is canvas-based drawing.
If you find createButton() isn't enough and/or other geometric forms are too tedious to manage manually via classes, you're gonna need some SVGElement vectorial-based library:
https://Developer.Mozilla.org/en-US/docs/Web/API/SVGElement
Dunno much about it. Just heard about Raphaël: 8->
I daresay you can even mix both p5.js & Raphaël in the same sketch. :ar!