1

I would like to make a scanner effect over an image in canvas similar to the thread How to animate scanner effect line with canvas but when add image clearRECT deletes the image below

                var x = 4,
                y = 4,
                speed = 1,
                isBottom = false;
                document.getElementById("canvas").innerHTML = "";
          
              var canvas = document.getElementById('canvas');
              ctx = canvas.getContext('2d');
              img = new Image();
              img.src = imagetag.src;
            
            img.onload = function() {
                canvas.width = img.width/2;
                canvas.height = img.height/2;
                ctx.drawImage(img, 0, 0, img.width/2, img.height/2); 
               
            } 
            
            function draw(imagetag) {
                img = new Image();
               img.src = imagetag.src;
               img.onload = function() {
                canvas.width = img.width/2;
                canvas.height = img.height/2;
                ctx.drawImage(img, 0, 0, img.width/2, img.height/2); 
               
            }  
                ctx.fillStyle = '#07C';
                ctx.lineCap = 'round';
                ctx.shadowBlur = 18;
                ctx.shadowColor = "#07C";
                ctx.fillRect(x, y, 210, 10); 
                if (!isBottom && y < canvas.height - 14) y += speed;
                else if (y === canvas.height - 14) isBottom = true; 
                if (isBottom && y > 4) y -= speed;
                else if (y === 4) isBottom = false;
                
                requestAnimationFrame(draw);
            }

            draw(imagetag);
           

1 Answers1

-1

No need for the duplicate new Image() declaration, we can do with just one, the way you have it you technically loading a new image on every frame, not very efficient...

See this sample:

var x = 4, y = 4, speed = 1
var canvas = document.getElementById('canvas');
var img = new Image();
var ctx = canvas.getContext('2d');

function draw() {
  canvas.width = img.width / 2;
  canvas.height = img.height / 2;
  ctx.drawImage(img, 0, 0, img.width / 2, img.height / 2);

  ctx.fillRect(x, y, 210, 10);
  y += speed
  if (y > canvas.height - 14 || y < 4) speed *= -1;

  requestAnimationFrame(draw);
}

img.onload = draw
img.src = "https://i.stack.imgur.com/UFBxY.png"
<canvas id="canvas"></canvas>

I simplified a lot of your code removed all the fill color and shadow to just focus on the problem, draw the scanner effect over an image, everything else was just a distraction, also your logic to change the position of Y was too complex, I simplified all that to just change the speed when we hit the borders

Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56