2017-01-06 185 views
0

我有一個問題。我正在使用JavaScript在Canvas中創建簡單的遊戲。圖片在電話後不顯示clearRect(),有誰知道,如何解決?畫布 - drawImage()後clearRect()

var left1 = 0; 
 
var context1 = document.getElementById('canvas1').getContext('2d'); 
 
render1(); 
 
function render1() { 
 
    var image = new Image(); 
 
    image.onload = function() { 
 
     context1.drawImage(image, left1, 0, 200, 200); 
 
    }; 
 
    image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png'; 
 
    left1++; 
 
    requestAnimationFrame(render1); 
 
} 
 

 
var left2 = 0; 
 
var context2 = document.getElementById('canvas2').getContext('2d'); 
 
render2(); 
 
function render2() { 
 
    context2.clearRect(0, 0, 500, 250); 
 
    var image = new Image(); 
 
    image.onload = function() { 
 
     context2.drawImage(image, left2, 0, 200, 200); 
 
    }; 
 
    image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png'; 
 
    left2++; 
 
    requestAnimationFrame(render2); 
 
}
canvas { 
 
    display: block; 
 
}
It works, but old images are not deleted: 
 
<canvas id="canvas1" height="250" width="500"></canvas> 
 

 
It doesn't work, because of clearRect(): 
 
<canvas id="canvas2" height="250" width="500"></canvas>

+1

爲什麼你是否在每個signle渲染調用中加載圖像? – pwolaq

回答

0

如果您嘗試動畫的圖像,其沒有必要做兩個帆布,而不是用一個定時器,我希望這將有助於

`

var left1 = 0; 
    var context1 = document.getElementById('canvas1').getContext('2d'); 
    var canvas1 = document.getElementById('canvas1'); 
    window.onload = init; 

    function init() { 
     setInterval(drawc, 1000/60); 
    }; 

    function drawc() { 
     if (left1 > canvas1.width) { 
      left1 = 0; 
     } 
     render1(); 
    } 


    function render1() { 

     with(context1) { 
      clearRect(0, 0, canvas1.width, canvas1.height); 
      var image = new Image(); 
      image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png'; 
      beginPath(); 
      drawImage(image, left1, 0, 200, 200); 
      closePath(); 
      fill(); 
      left1++; 
      // requestAnimationFrame(render1); 
     } 
    };