我是编码的新手,我需要一些帮助。我有一个开始按钮<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);
但是当然,当我加载游戏时,它加载了绘画功能,而无需单击开始按钮 所以当我单击开始按钮而不是重新加载游戏时,如何使该函数被调用
答案 0 :(得分:0)
您正在将函数Error in m1 == m3 : comparison of these types is not implemented
作为函数draw
中的处理程序传递,因此将自动调用函数requestAnimationFrame
。
拥抱函数draw
并按如下所示绑定事件addEventListener
:
click
答案 1 :(得分:0)
定义函数后立即调用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>