【问题标题】:How do i make a button call a function?如何让按钮调用函数?
【发布时间】:2020-05-27 13:10:41
【问题描述】:

我是编码新手,我需要一些帮助。我有一个开始按钮<button id="startBtn" onclick="draw()">START</button> 我想要这个开始按钮来调用我的绘图函数

    function draw() {
    drawWalther();
    rain();

    if (rightPressed && (waltherX + waltherWidth) < 865) {
        waltherX += waltherDx;
    } else if (leftPressed && waltherX > -54){
        waltherX -= waltherDx;
    }

    if (y + dy > c.height - 100 || y + dy < 0) {
        dy = 0;
    }

    if (rightPressed && (waltherheadX + waltherheadWidth) < 900) {
        waltherheadX += waltherheadDx;
    } else if (leftPressed && waltherheadX > 50){
        waltherheadX -= waltherheadDx;
    }
    x += dx;
    y += dy;

    requestAnimationFrame(draw);
} 
requestAnimationFrame(draw);

当然,当我加载游戏时,它会加载绘图功能,而无需我单击开始按钮 那么如何在单击开始按钮而不是在重新加载游戏时调用该函数

【问题讨论】:

标签: javascript function button


【解决方案1】:

您将函数 draw 作为函数 requestAnimationFrame 中的处理程序传递,因此函数 draw 会被自动调用。

拥抱函数addEventListener并绑定事件click如下:

1。移除 onClick 属性

function draw() {
  drawWalther();
  rain();

  if (rightPressed && (waltherX + waltherWidth) < 865) {
    waltherX += waltherDx;
  } else if (leftPressed && waltherX > -54) {
    waltherX -= waltherDx;
  }

  if (y + dy > c.height - 100 || y + dy < 0) {
    dy = 0;
  }

  if (rightPressed && (waltherheadX + waltherheadWidth) < 900) {
    waltherheadX += waltherheadDx;
  } else if (leftPressed && waltherheadX > 50) {
    waltherheadX -= waltherheadDx;
  }
  x += dx;
  y += dy;

  requestAnimationFrame(draw);
}
document.querySelector("#startBtn").addEventListener("click", draw));

【讨论】:

    【解决方案2】:

    定义函数后立即调用requestAnimationFrame(draw)。这会立即运行该功能,因此不会等待按钮。如果删除函数定义之后的实例,它将等待函数。

    简化示例:

    <script>
    function draw() {
        // some code
        requestAnimationFrame(draw);
    };
    </script>
    <button onclick="draw()"></button>
    

    您的新代码:

    <script>
        function draw() {
        drawWalther();
        rain();
    
        if (rightPressed && (waltherX + waltherWidth) < 865) {
            waltherX += waltherDx;
        } else if (leftPressed && waltherX > -54){
            waltherX -= waltherDx;
        }
    
        if (y + dy > c.height - 100 || y + dy < 0) {
            dy = 0;
        }
    
        if (rightPressed && (waltherheadX + waltherheadWidth) < 900) {
            waltherheadX += waltherheadDx;
        } else if (leftPressed && waltherheadX > 50){
            waltherheadX -= waltherheadDx;
        }
        x += dx;
        y += dy;
    
        requestAnimationFrame(draw);
    } 
    </script>
    <button id="startBtn" onclick="draw()">START</button>
    

    【讨论】:

    • 非常感谢,非常感谢 :)
    • 如果答案解决了您的问题,您可以通过按标志将其标记为已接受。乐于助人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多