Υποενότητα 9.1: p5 Γεγονότα
Υποενότητα 9.1: p5 Γεγονότα
- Εισαγωγή στα γεγονότα - events
- mouseX and mouseY
- mouseClicked()
- mouseIsPressed()
mouseIsPressed
Η mouseIsPressed
είναι μια μεταβλητή boolean που μεταβάλλεται από false σε true όταν πατηθεί το ποντίκι.
Αυτή η μεταβλητή παραμένει αληθής, όσο είναι πατημένο το ποντίκι, και όταν απελευθερωθεί, αλλάζει ξανά σε ψευδής.
Example
Ακολουθεί ένα παράδειγμα κώδικα που σχεδιάζει έλλειψη στη θέση που δείχνει το ποντίκι, όσο πιέζεται το ποντίκι:
function setup() {
createCanvas(800, 500);
}
function draw() {
// set background inside draw so that the ellipse will not leave traces
background('#D66761');
fill(241, 213, 145);
// if the mouse is pressed
if (mouseIsPressed){
// an ellipse will be drawn in the position where the mouse is pointing
ellipse(mouseX, mouseY, 50);
}
}
Μπορείτε να δείτε το αποτέλεσμα του παραπάνω κώδικα, click here.
Exercise
- Open your Visual Studio editor and the
p5yourName
folder. - Open the file
ex812.js
in your editor and save it asex914.js
- Open the file
ex812.html
in your editor and save it asex914.html
- In the
ex914.html
file, update the link toex914.js
from exersice812.js - Go to the
index.html
file and create, underModule 9
, alink
to theex914.html
file with the title "mouseIsPressed".
Modify the ex914.js
file to create a drawing tool which will be drawing ellipses as long as the mouse is pressed. Also, include two other ellipses, a red and a green one. Make the drawing tool change the color of the ellipses it is drawing to red, if the user clicks inside the red ellipse and to green if the user clicks inside the green ellipse. You can see here an example.
let mycolor = 'white';
function setup() {
createCanvas(800, 500);
background('#D66761');
}
function draw() {
// this color will change every time the mouse clikcs the red or green ellipse
fill(mycolor);
// if the mouse is pressed
if (mouseIsPressed){
// an ellipse will be drawn in the position where the mouse is pointing
ellipse(mouseX, mouseY, 20);
}
fill ('red');
ellipse (600,250,50);
fill('green');
ellipse (600,350,50);
}
// everytime the mouse is clicked
function mouseClicked(){
// if the mouse x and y position is inside the red ellipse
if (mouseX >=550 && mouseX <=650 && mouseY >=200 && mouseY <=300){
//change its color to red
mycolor = 'red';
}
// if the mouse x and y position is inside the green ellipse
if (mouseX >=550 && mouseX <=650 && mouseY >=300 && mouseY <=400){
//change its color to green
mycolor = 'green';
}
}
Κάντε μια Git commit με το μήνυμα "mouseIsPressed".
- Δείτε περισσότερα για τη μεταβλητή mouseIsPressed