three.js 将图片马赛克化的示例代码
程序员文章站
2022-09-11 18:50:30
这篇郭先生来说说buffergeometry,类型化数组和粒子系统的使用,并且让图片有马赛克效果(同理可以让不清晰的图片清晰化),如图所示1. 解析图片解析图片和上一篇一样initcanvas() {...
这篇郭先生来说说buffergeometry,类型化数组和粒子系统的使用,并且让图片有马赛克效果(同理可以让不清晰的图片清晰化),如图所示
1. 解析图片
解析图片和上一篇一样
initcanvas() { canvas = document.createelement('canvas'); content = canvas.getcontext('2d'); canvas.width = 1600; canvas.height = 1200; img = new image(); img.crossorigin = '*'; img.src = "/static/images/base/girl.jpg"; img.onload = () => { content.drawimage(img, 0, 0, canvas.width, canvas.height); imgdate = content.getimagedata(0, 0, canvas.width, canvas.height); this.createpotcloud(); //创建点云 }; }
2. 操作像素点
createpotcloud() { if (points) { scene.remove(points) } let cw = math.floor(canvas.width / size); let ch = math.floor(canvas.height / size); particles = cw * ch; geometry = new three.buffergeometry(); positions = new float32array(math.floor(particles * 3)); positions_af = new float32array(math.floor(particles * 3)); var colors = new float32array(math.floor(particles * 3)); for (var i = 0; i < positions.length; i += 1) { positions[3 * i] = - canvas.width / 2 + (i % cw) * size; positions[3 * i + 1] = canvas.height / 2 + math.floor((-1 - i) / cw) * size; positions[3 * i + 2] = 0; let selectpos = size * (i % cw) + math.floor(i / cw) * cw * size * size; colors[3 * i] = imgdate.data[4 * selectpos] / 255.0; colors[3 * i + 1] = imgdate.data[4 * selectpos + 1] / 255.0; colors[3 * i + 2] = imgdate.data[4 * selectpos + 2] / 255.0; } geometry.setattribute('position', new three.bufferattribute(positions, 3)); geometry.setattribute('color', new three.bufferattribute(colors, 3)) geometry.dynamic = true; geometry.attributes.position.needsupdate = true; var material = new three.pointsmaterial({ size: size, vertexcolors: three.vertexcolors }) points = new three.points(geometry, material); points.name = 'points'; scene.add(points); loaded = true; },
可以不用纠结代码,核心思想其实我们只需要每隔一定的颜色点取出一个颜色点,然后将这个颜色赋予到geometry的color属性上,就可以了,也可以每隔两行、两列取一个点,但是图片上面的点是一维的,所以需要一些数学方法,
如图所示,原理很简单哦。将不清晰的图片清晰化,就是需要插入更多的像素点,插入的像素点,需要根据已存在的像素点的颜色进行插值,比如原图的像素点1为0xffffff,像素点2的颜色为0xdddddd,则插在两个像素点之间像素点的颜色为0xeeeeee,以此类推。
以上就是three.js 将图片马赛克化的示例代码的详细内容,更多关于three.js 将图片马赛克化的资料请关注其它相关文章!