使用canvas在秒内逐像素显示图片

Using canvas to display a picture pixel by pixel within secs

出于学习目的,我试图在几秒钟内在 canvas 中逐个像素地显示图像,下面是我编写的代码

var timeStamps = [];
var intervals = [];
var c = document.getElementById('wsk');
var ctx = c.getContext("2d"),
    img = new Image(),
    i;
img.onload = init;
img.src = "http://placehold.it/100x100/000000";
var points = [];
function init(){
  ctx.canvas.width = img.width;
  ctx.canvas.height = img.height;
  for (i=0; i<img.width*img.height; i++) {
    points.push(i);
  }
  window.m = points.length;
  var sec = 10; //animation duration

  function animate(t) {
    timeStamps.push(t);
    var pointsPerFrame = Math.floor(img.width*img.height/sec/60)+1;
    var start = Date.now();
    for (j=0; j<pointsPerFrame; j++) {
      var i = Math.floor(Math.random()*m--); //Pick a point
      temp = points[i];
      points[i] = points[m];
      points[m] = temp;   //swap the point with the last element of the points array
      var point = new Point(i%img.width,Math.floor(i/img.width));  //get(x,y)
      ctx.fillStyle = "rgba(255,255,255,1)";
      ctx.globalCompositeOperation = "source-over";
      ctx.fillRect(point.x,point.y,1,1); //DRAW DOZENS OF POINTS WITHIN ONE FRAME
    }
    ctx.globalCompositeOperation = "source-in";//Only display the overlapping part of the new content and old cont
    ctx.drawImage(img,0,0); //image could be with transparent areas itself, so only draw the image on those points that are already on screen, exluding points that don't overlap with the image.
    var time = Date.now()-start;
    intervals.push(time);
    if( m > 0 ) requestAnimationFrame(animate);
  }
  animate();
}

function Point(x,y) {
  this.x = x;
  this.y = y;
}

现场测试:www.weiwei-tv.com/test.php。 我原以为这些点会完全随机出现并最终填满整个 100*100 canvas。真正发生的是每次只显示图片的上半部分,而下半部分的许多点都被遗漏了。我想问题出在我用来随机拾取点的技术上,我从这个 page 得到它,但我找不到任何错误。

我注意到的另一件事是 intervals 大部分是 1 毫秒或 0 毫秒,这意味着 javascript 花费很少的时间绘制 100*100/10/60 点并在每一帧内在其上绘制图像.但是timeStamps之间的差异大多在30~50ms,应该是16ms(1000/60)左右。我不确定这是否也在我的代码失败中起作用。

问题是您正在使用点数组的索引来计算点坐标。您需要使用所选点的值(移动到第 m 个位置)。

所以,改变

var point = new Point(i%img.width,Math.floor(i/img.width));

var point = new Point(points[m]%img.width,Math.floor(points[m]/img.width));