我正在可汗学院学习 javascript,需要帮助来创建单选按钮。对于这段代码,我宁愿不使用 html 标签。
我最初有一个表情符号,它会随着 mouseX 和 mouseY 的移动而移动。但是,在添加按钮功能(有效)后,表情符号不起作用。这似乎是一个非此即彼的情况。有没有办法我可以重新排序我的代码,这样两者都可以工作?
基本上,我想要一个随 mouseX 和 mouseY(鼠标的 X、Y 位置)移动的表情符号,并且能够添加一个按钮功能,该功能在表情符号的顶部或底部添加一个圆圈,具体取决于单击哪个按钮。我希望表情符号在添加圆圈后仍然能够移动。右侧底部的两个矩形是按钮。白色圆圈是表情符号,背景是粉红色圆圈和粉红色空白屏幕。
我尝试在绘图内、绘图外或绘图表情内使用 mouseClicked 的各种组合重新排序代码。但到目前为止,我还没有找到一种可以给我正在寻找的东西的方法。是否可以使用纯 javascript 来做到这一点?TIA
编辑:
这是我正在处理我的代码的链接。我还没有把它放在 jsfiddle 中,因为我还不知道如何使用 html 标签和添加代码。 https://www.khanacademy.org/computer-programming/spin-off-of-simple-buttons-with-functionsobject-params/4602551803707392
至于解释我想要发生的事情,那是在我帖子的第 3 段中吗?如果还不清楚,请告诉我。
到目前为止,这是我的代码:
var x = 250;
var y = 300;
var btnwidth = 100;
var btnheight = 30;
//to highlight the button that is pressed
var highlightbox = function(hix, hiy, hiw, hih) {
noFill();
stroke(56, 247, 8);
strokeWeight(5);
rect(hix, hiy, hiw, hih);
};
//outer circle of the emoji face, the idea was for it to move along with the mouse but now it doesn't
var X = constrain(mouseX, 190, 210);
var Y = constrain(mouseY, 115, 140);
var W = 160;
var H = W;
var drawEmoji = function() {
var X = constrain(mouseX, 190, 210);
var Y = constrain(mouseY, 115, 140);
var W = 160;
var H = W;
fill(247, 242, 242);
stroke(0, 51, 255);
strokeWeight(3);
ellipse(X,Y,W,H);
};
//background behind the emoji
var drawBackground = function() {
background(250, 187, 187);
fill(191, 130, 130);
stroke(255, 0, 0);
strokeWeight(3);
ellipse(200,200,400,400);
fill(247, 207, 247);
rect(x, y, btnwidth, btnheight);
fill(173, 207, 250);
rect(x, y+50, btnwidth, btnheight);
};
drawBackground();
drawEmoji();
var draw = function() {
//mouse click function for the button, when it's clicked a circle appears on the emoji
mouseClicked = function(){
drawBackground();
drawEmoji();
if (mouseX > x && mouseX < (x + btnwidth) && mouseY > y && mouseY < (y + btnheight)) {
highlightbox(x, y, btnwidth, btnheight);
stroke(68, 0, 255);
fill(247, 207, 247);
ellipse(X - 49,Y - 50,W/3,H/3);
}
else if (mouseX > x && mouseX < (x + btnwidth) && mouseY > y + 50 && mouseY < (y + 50 + btnheight)) {
highlightbox(x, y + 50, btnwidth, btnheight);
stroke(68, 0, 255);
fill(173, 207, 250);
ellipse(X+1,Y+100,W/3,H/3);
}
};
};