Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么clearRect()没有从画布中删除任何内容?_Javascript_Html_Canvas - Fatal编程技术网

Javascript 为什么clearRect()没有从画布中删除任何内容?

Javascript 为什么clearRect()没有从画布中删除任何内容?,javascript,html,canvas,Javascript,Html,Canvas,我想清理整个画布。但是使用clearRect()没有任何作用。那么,我如何才能从画布上删除绘制的图片 <canvas id="myCanvas" width="600" height="580"></canvas> <script> window.onload = function() { canv = document.getElementById("myCanvas"); ctx = canv.getContext(

我想清理整个画布。但是使用clearRect()没有任何作用。那么,我如何才能从画布上删除绘制的图片

<canvas id="myCanvas" width="600" height="580"></canvas>
<script>
    window.onload = function() {
        canv = document.getElementById("myCanvas");
        ctx = canv.getContext("2d"); 
                falcon = document.getElementById("milenium_falcon");
        ctx.drawImage(falcon, 315, 500, 75, 75);
        document.addEventListener("keydown",keyPush);
        setInterval(game,1000/15);
    }
    x = 0;
    function game() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        ctx.drawImage(falcon, 315 - x, 500, 75, 75);
    }
    function keyPush(evt) {
        switch(evt.keyCode) {
            case 37:
                x -= 5;
                break;
            case 39:
                x += 5;
                break;
        }
    }
</script>

window.onload=函数(){
canv=document.getElementById(“myCanvas”);
ctx=canv.getContext(“2d”);
falcon=document.getElementById(“milenium_falcon”);
ctx.drawImage(猎鹰,315500,75,75);
文件。添加了文本列表(“按键向下”,按键推动);
设定间隔(游戏,1000/15);
}
x=0;
函数游戏(){
clearRect(0,0,canvas.width,canvas.height);
drawImage(猎鹰,315-X500,75,75);
}
功能键推送(evt){
开关(evt.keyCode){
案例37:
x-=5;
打破
案例39:
x+=5;
打破
}
}

在调用
.clearRect()
时,使用变量
canvas
而不是
canv
。如果您改为使用这一行,它应该可以工作:

ctx.clearRect(0, 0, canv.width, canv.height);