HTML5 ( canvas, javascript ) 图像,做痕迹

HTML5 ( canvas, javascript ) The image, makes traces

enter image description here首先对不起我的英语。其次,我的 javascript 有问题。 我试图制作类似 baner 的东西,它会改变内部图像。但是,当我想继续我的脚本时,canvas 字段中的最后一张图片让我遇到了问题。它使留下痕迹。这是我的代码。

<html>
<head>
    <link rel="stylesheet" href="style.css">
    <script>
       
       var cat= new Image();

       function init(){
           cat.src = 'cat.png';
           window.requestAnimationFrame(draw);
       }

       function draw() {

        var context = document.getElementById('spin').getContext('2d');
        
        context.clearRect(0, 0, 530, 110);
        context.save();
        context.translate(-1, 0);
        
     
        context.drawImage(cat, 5, 0);
        context.drawImage(cat, 110, 0);
        context.drawImage(cat, 215, 0);
        context.drawImage(cat, 320, 0);
        context.drawImage(cat, 425, 0);
        context.drawImage(cat, 530, 0); /// its an image with problem
        
        
        
        
        

        window.requestAnimationFrame(draw);

       }

       init();

     
    </script>
</head>
<body>

 <div class="roulette">
       <canvas id="spin" width="530" height="110"></canvas>
    </div>

</body>

在javascript中加载图像时,请注意此过程是异步的。给Image元素的src属性赋值时,需要在该元素的onload回调函数中获取该元素。否则,绘制到canvas时,元素可能没有完全加载相应的图像资源。

const img = new Image()

img.onload = function () {
  // img fully loaded here
}

img.src = 'path/to/image/sources'

你从不调用 context.restore(),所以你在内存中堆积了很多 CanvasStates(这会使你的整个应用程序在几分钟内变慢),更直接值得注意的是,你的上下文转换永远不会重置,这意味着在第二次调用时,坐标 0, 0 将是坐标 -1, 0 处的像素,而在第三次调用时 -2, 0 等,这将使您对 clearRect() 的调用再错过一个像素每次都在 canvas 的右侧。

目前还不清楚您在寻找什么,但要正确清除上下文,请在调用 clearRect() 之前调用 context.setTransform(1, 0, 0, 1, 0, 0),这会将转换矩阵重置为其单位矩阵。
然后,如果您想通过不断减小的值来翻译您的上下文,请将该值存储在一个变量中,并在您对 translate().
的调用中使用它 最后,删除对 save() 的调用,因为它不需要。

let x = 0; // the variable where we store the current offset
var cat = new Image();

function init() {
  cat.src = 'https://picsum.photos/110/110';
  // always wait for your image has loaded before doing anything with it
  cat.onload = evt =>
    window.requestAnimationFrame(draw);
}

function draw() {

  var context = document.getElementById('spin').getContext('2d');
  // update the offset
  x -= 1;
  // last image is hidden, stop the loop?
  if (x < (530 + 110) * -1) {
    return;
  }
  // reset the context matrix
  context.setTransform(1, 0, 0, 1, 0, 0);
  // clear the full canvas
  context.clearRect(0, 0, 530, 110);
  // set the updated offset
  context.translate(x, 0);

  context.drawImage(cat, 5, 0);
  context.drawImage(cat, 110, 0);
  context.drawImage(cat, 215, 0);
  context.drawImage(cat, 320, 0);
  context.drawImage(cat, 425, 0);
  context.drawImage(cat, 530, 0);

  window.requestAnimationFrame(draw);

}

init();
<canvas width="530" height="110" id="spin"></canvas>