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

时间:2016-05-09 12:44:04

标签: javascript animation requestanimationframe

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

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-t​​v.com/test.php。 我期待这些点总是随机出现并最终填满整个100 * 100画布。实际发生的是每次只显示图片的上半部分,但是下半部分中的许多点都会丢失。我想问题是我用来随机拾取点的技术,我从page得到它,但是我找不到任何错误。

我注意到的另一件事是intervals大多是1ms或0ms,这意味着javascript花费很少的时间绘制100*100/10/60点并在每帧内绘制图像。但是,timeStamps之间的差异大多是30~50ms,应该是大约16ms(1000/60)。我不确定这是否也会导致我的代码失败。

1 个答案:

答案 0 :(得分:1)

问题是您正在使用points数组的索引来计算点坐标。您需要使用所选点的值(移动到第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));