为了学习,我尝试在几秒钟内在画布上逐像素显示图像,下面是我编写的代码。
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.wewe-tv.com/test.php。我原以为这些点会随机出现,最终填写完整个100*100张画布。真正发生的是,每次只有图片的上半部分被显示,但许多点在下半部被遗漏。我想问题在于我使用的随机拾取点的技术,我从这个页面中得到了它,但是我没有发现它有什么问题。
我注意到的另一件事是,intervals大多是1ms或0ms,这意味着javascript花费很少的时间绘制100*100/10/60点,并在每一个帧中在其上绘制图像。但timeStamps的差异主要为30~50 be,约为16 be(1000/60)。我不确定这是否也与我的代码失败有关。
发布于 2016-05-09 13:09:06
问题是,您正在使用点数组的索引来计算点坐标。您需要使用所选点的值(移动到第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));https://stackoverflow.com/questions/37116169
复制相似问题