Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.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 画布中的Context.clearRect不起作用_Javascript_Html_Canvas_Html5 Canvas_Drawimage - Fatal编程技术网

Javascript 画布中的Context.clearRect不起作用

Javascript 画布中的Context.clearRect不起作用,javascript,html,canvas,html5-canvas,drawimage,Javascript,Html,Canvas,Html5 Canvas,Drawimage,如果我得到一张图片,并想画它移到右边,它的工作。但当我添加clearRect时,图片就消失了。如何将类似的代码与正确的方法结合使用,以便clearRect能够工作 这是我的密码: <html> <head> <style> #canvas_id{ border:1px solid red; } </style> </head> <body> <canvas id="canvas_id"></canv

如果我得到一张图片,并想画它移到右边,它的工作。但当我添加clearRect时,图片就消失了。如何将类似的代码与正确的方法结合使用,以便clearRect能够工作

这是我的密码:

<html>
<head>
<style>
#canvas_id{
border:1px solid red;
 }
 </style>
 </head>
<body>

<canvas id="canvas_id"></canvas>
<script>
var canvas = document.getElementById( "canvas_id" );
var Context = canvas.getContext( "2d" );
var x1 = 10;
var x2 = 10;

var img = new Image();
img.src = "example.jpg";
img.onload = function(){ Context.drawImage( img, x1, x2,20,20); }

draw();

function draw(){
  window.requestAnimationFrame(draw);

 Context.clearRect(0,0,innerWidth,innerHeight);

 var Img = new Image();
 Img.src = "example.jpg";
 Img.onload = function(){ Context.drawImage( Img, x1, x2,20,20); }


 x1 = x1 +1;


}
</script>
</body>

如果我用fillRect而不是图像作为矩形,那么代码可以工作。

只加载一次图像

加载映像始终是异步的,即使在缓存时也是如此。 requestAnimationFrame回调将在下一次绘制屏幕之前调用。 下面是代码中发生的情况的示意图:

clearRect start_to_load_Img || ... img.loaded=>drawImage ... clearRect start_to_load_Img || etc.
                            ^                                                            ^
               render new frame to screen                                    render new frame to screen
正如您所看到的,每次在两帧之间加载图像时。但就在下一帧传递到屏幕之前,您应该已经清除了它

所以一个固定的代码看起来像

// load your image only once
var img = new Image();
img.src = "example.jpg";

draw();

function draw(){
  window.requestAnimationFrame(draw);

  Context.clearRect(0,0,innerWidth,innerHeight);
  if(img.naturalWidth) { // check it has loaded
    Context.drawImage(img, x1, x2,20,20);
  }
 ...

为什么要添加clearRect?你想实现什么?每次在一个位置上都会重新创建图像,如果我不使用clearRect之类的东西,旧位置就不清晰,所以动画看起来很糟糕和错误:/I我只想用canvas将图像转换到右侧。因为我以后需要canvas来完成其他一些事情,但这并不重要:-