我想创建一个button2
以在每次单击时显示两只猫中的另一只。
我想通过用JavaScript而不是html编写代码来做到这一点。
问题细节:
1)
由于我只需要显示两张图像,因此我以为只需要创建一个数组cats
,但是console.log(cats)
告诉我此时数组中没有对象。因此,我创建了另一个数组conans
,但不确定如何从此处继续。
2)另外,由于我只有两个图像可供选择,random
也不是必须的。也许如果陈述更好。但是,我再次不确定如何以及在何处编写它们。
3)我不确定要在button2.mousePressed()
中放入什么参数。
任何帮助将不胜感激。
let bgColor;
// an array to store ??
let conans = [];
// an array to store 2 images to randomly choose from
let cats = [];
let button;
let button2;
function preload() {
for (let i = 0; i < 2; i++) {
cats[i] = loadImage(`conan${i}.jpg`);
console.log(cats);
}
}
function setup() {
canvas = createCanvas(200, 200);
bgColor = color(200);
for (let i = 0; i < 2; i++) {
let cat = random(cats);
let conan = new Conan(x, y, w, h, cat);
conans.push(conan);
}
button = createButton("change background");
button.mousePressed(changeColor);
button2 = createButton("change cat");
button2.mousePressed(changeImage);
}
function changeImage() {
if(img.src.match('conan0.jpg')); {
return img;
} else {
img.src = 'conan1.jpg';
}
}
function changeColor() {
bgColor = color(random(255), random(255), random(255));
}
/* Instead of making a global variable,
function mousePressed() {
changeColor();
}
*/
function draw() {
background(bgColor);
fill(225, 28, 168);
rect(100, 100, 50, 50);
for (let cat of cats) {
conan.show();
}
}
class Conan {
constructor(x = 100, y = 100, w = 100, h = 100, img) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.conan = img;
}
show() {
image(this.conan, this.x, this.y, this.w, this.h);
}
}