我正在为一个带有交互式画布的美术课做一个项目。我的目标是让小动物在被点击时发出声音并“移动”。我试图在不创建类的情况下执行此操作,因为出于某种原因我无法在类中使用图像。我正在尝试尽可能轻松地做到这一点。
我所说的“移动”是什么意思,是我试图让背景图像以不同的姿势出现在他们身上。默认背景是动物的风景,然后当鼠标在它们上面时,会显示不同的图像,动物的姿势不同。
TLDR:需要的功能是当鼠标在某个区域上方时它会显示图像并播放声音。
function preload() {
birdsSound = loadSound("sounds/birds.mp3");
backgrnd = loadImage("images/backgrnd.png");
birdsImage = loadImage("images/birds.png");
}
function setup() {
createCanvas(1000, 750);
birdsImage.mouseOver(birdsFUNC);
}
function draw() {
image(backgrnd,0,0);
}
function birdsFUNC() {
birdsSound.play();
image(birdsImage,0,0);
}
另外我应该补充一点,我是 非常 在 MATLAB 以外的任何地方编码,所以 p5 是全新的。像我五岁一样向我解释。
p5.Image
使用 loadImage()
创建的对象)不是在画布中具有位置的图形元素。它只是可以绘制到画布上的图像的像素数据。图像和 p5.js 中的所有其他图形元素都以 immediate 模式 绘制到画布上,因此也不是在画布上具有位置的持久元素。为了在特定图形元素上实现鼠标悬停或命中检测等功能,您必须根据鼠标位置(通过mouseX
和mouseY
)以及绘制相关图形元素的坐标自行实现。这是一个简单的例子:
let img;
let imgHover;
let vel;
let pos;
function preload() {
img = loadImage('https://www.paulwheeler.us/files/AnimFrame00.png');
imgHover = loadImage('https://www.paulwheeler.us/files/AnimFrame01.png');
}
function setup() {
createCanvas(windowWidth, windowHeight);
vel = p5.Vector.random2D();
pos = createVector(random(0, width - img.width), random(0, height - img.height));
}
function draw() {
background(200);
// check if the mouse is over the image or not
let hover =
mouseX >= pos.x && mouseX <= pos.x + img.width &&
mouseY >= pos.y && mouseY <= pos.y + img.height;
if (hover) {
image(imgHover, pos.x, pos.y);
} else {
image(img, pos.x, pos.y);
}
// Move the image
pos.add(vel);
if (pos.x < 0) {
pos.x = -pos.x;
vel.x = -vel.x;
} else if (pos.x + img.width > width) {
pos.x = width - (pos.x + img.width - width) - img.width;
vel.x = -vel.x;
}
if (pos.y < 0) {
pos.y = -pos.y;
vel.y = -vel.y;
} else if (pos.y + img.height > height) {
pos.y = height - (pos.y + img.height - height) - img.height;
vel.y = -vel.y;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
除了将图像写入画布并检查坐标之外的另一种选择是使用
createImg
,然后将mouseX
处理程序添加到该element:
let img;
function setup() {
noLoop();
noCanvas();
img = createImg("http://placekitten.com/200/160", "kitten");
img.mouseOver(() => console.log("mouse in"));
img.mouseOut(() => console.log("mouse out"));
img.mouseMoved(() => console.log("mouse moved"));
img.mouseClicked(() => console.log("mouse clicked"));
img.mouseReleased(() => console.log("mouse released"));
img.mouseWheel(event => {
event.preventDefault(); // prevent scrolling
console.log("mouse wheel");
});
}
function draw() {
background(0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>