gpt4 book ai didi

javascript - 使用canvas在几秒钟内逐像素显示图片

转载 作者:行者123 更新时间:2023-12-03 06:59:36 25 4
gpt4 key购买 nike

出于学习目的,我尝试在几秒钟内在 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-t​​v.com/test.php。我预计这些点会完全随机出现并最终填满整个 100*100 Canvas 。真实发生的情况是每次只显示图片的上半部分,但下半部分的许多点都被遗漏了。我想问题出在我用来随机拾取点的技术上,我从这个 page 中得到它。 ,但我找不到任何错误。

我注意到的另一件事是,间隔大多为1ms或0ms,这意味着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));

关于javascript - 使用canvas在几秒钟内逐像素显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37116169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com