0

我正在可汗学院学习 javascript,需要帮助来创建单选按钮。对于这段代码,我宁愿不使用 html 标签。

我最初有一个表情符号,它会随着 mouseX 和 mouseY 的移动而移动。但是,在添加按钮功能(有效)后,表情符号不起作用。这似乎是一个非此即彼的情况。有没有办法我可以重新排序我的代码,这样两者都可以工作?

基本上,我想要一个随 mouseX 和 mouseY(鼠标的 X、Y 位置)移动的表情符号,并且能够添加一个按钮功能,该功能在表情符号的顶部或底部添加一个圆圈,具体取决于单击哪个按钮。我希望表情符号在添加圆圈后仍然能够移动。右侧底部的两个矩形是按钮。白色圆圈是表情符号,背景是粉红色圆圈和粉红色空白屏幕。

我尝试在绘图内、绘图外或绘图表情内使用 mouseClicked 的各种组合重新排序代码。但到目前为止,我还没有找到一种可以给我正在寻找的东西的方法。是否可以使用纯 javascript 来做到这一点?TIA

编辑:

到目前为止,这是我的代码:

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);
    }

 };

};
4

1 回答 1

0

这个问题已有 6 个月的历史,但我在 Khan 上注意到您没有更改您在此处发布的代码;所以我假设你仍然可能想要完成它。

我不会给你具体的代码来修复它(那是你的工作!),但这里有一些指示。

首先,您需要将 mouseClicked 函数移出 draw 函数,并完全移除 draw 函数。draw 函数在定义后会被连续调用,并且即使没有鼠标操作发生也用于动画。您目前只想在使用鼠标执行某些操作时进行绘制。连续画是大材小用!

其次,添加一个全局变量来指示是否必须绘制圆,如果必须绘制,是顶部还是底部。在 mouseClicked 函数中,您不能绘制圆圈 - 只需将此变量设置为应有的值,然后为背景和表情符号调用两个绘制函数。

添加一个 mouseMoved 函数来调用您的绘图函数。

在表情符号的绘制函数中,测试您的全局变量以决定在哪里绘制圆(或不绘制它)。

于 2016-02-08T09:07:54.083 回答