我是编码新手,需要帮助。我有一个开始按钮<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);
但是,当我加载游戏时,它加载了绘画功能,而无需单击开始按钮因此,当我单击开始按钮而不是重新加载游戏时,如何使该函数调用]
您将函数draw
作为处理程序传递给函数requestAnimationFrame
,因此将自动调用函数draw
。
拥抱函数addEventListener
并如下绑定事件click
:
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));
您在定义函数后立即调用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>