Canvas - drawImage() after clearRect()

1.5k views Asked by At

I have a problem. I am creating simple game in Canvas using JavaScript. Image doesn't display after call clearRect(), does anyone know, how to solve it?

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

There are 1 answers

0
A.Abdelhak On

if you try to animate your image , its not necessary to make two canvas instead use a timer , i hope this will help

`

    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);
        }
    };