(编辑:jimmy 日期: 2024/11/15 浏览:2)
这篇郭先生来说说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 将图片马赛克化的资料请关注其它相关文章!