ThreeJs制作模型图片

        这个标题名字可能有歧义,只是不知道如何更好的表达,总之就是将图片的像素转换成3D场景的模型,并设置这个模型的颜色,放到像素点对应的位置从而拼接成一个图片,起因是上文中用js分解了音乐,实现了模型跳动效果,既然音频可以分解,那图片应该也可以,所以就有个这篇博客。

        大概得实现逻辑是这样的,先找一个图片,像素要小,越小越好,要有花纹,然后用canvas将图片的每个像素拆解出来,拆解后可以获得这个图片每个像素的位置,颜色,用集合保存每个像素的信息,在3D场景中循环,有了位置和颜色后,在循环中创建一个个正方体,将正方体的位置设置为像素的位置,y轴方向为1,创建贴图,并将贴图的颜色改为像素点的颜色,全部循环后就得到一副用正方体拼接出来的图片了。但是如果你的图片分辨率高,那么拆解出来的像素点很多,就需要筛选掉一些,否则浏览器会卡死,所以强调用分辨率低的图片。

这里先找一副图片:

        下面开始代码:

首先创建场景,相机,灯光,渲染器等:

 initScene(){scene = new THREE.Scene();},initCamera(){this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);this.camera.position.set(200,400,200);},initLight(){//添加两个平行光const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);directionalLight1.position.set(300,300,600)scene.add(directionalLight1);const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);directionalLight2.position.set(600,200,600)scene.add(directionalLight2);},
initRenderer(){this.renderer = new THREE.WebGLRenderer({ antialias: true });this.container = document.getElementById("container")this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);this.renderer.setClearColor('#AAAAAA', 1.0);this.container.appendChild(this.renderer.domElement);},initControl(){this.controls = new OrbitControls(this.camera, this.renderer.domElement);this.controls.enableDamping = true;this.controls.maxPolarAngle = Math.PI / 2.2;      // // 最大角度},initAnimate() {requestAnimationFrame(this.initAnimate);this.renderer.render(scene, this.camera);},

然后封装一个用canvas分解图片的方法

getImagePixels(image) {return new Promise((resolve) => {const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');canvas.width = image.width;canvas.height = image.height;ctx.drawImage(image, 0, 0);const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);const data = imageData.data;const pixels = [];for (let i = 0; i < data.length; i += 4) {const x = (i / 4) % canvas.width;const y = Math.floor((i / 4) / canvas.width);const r = data[i];const g = data[i + 1];const b = data[i + 2];const a = data[i + 3];pixels.push({ x, y, r, g, b, a });}resolve(pixels); // 返回所有像素的数据数组});},

然后调用这个方法获取到像素点集合信息,再循环这个集合,这里为了不卡顿,选择每40个像素点才生成一个模型,也就是下面的i%40===0的判断,

initBox(){const img = new Image();img.src = '/static/images/image.jpg';let geometry = new THREE.BoxGeometry(1, 1, 1);img.onload = async () => {let boxModel = []try {const allPixels = await this.getImagePixels(img);for (let i = 0; i < allPixels.length; i++) {if(i%40 === 0) {let r = allPixels[i].r;let g = allPixels[i].g;let b = allPixels[i].b;let x = allPixels[i].x;let y = allPixels[i].y;let cubeMaterial = new THREE.MeshPhysicalMaterial({color: 'rgb(' + r + ', ' + g + ', ' + b + ')'});this.boxMaterial.push(cubeMaterial)let mesh = new THREE.Mesh(geometry.clone(), cubeMaterial);mesh.position.set(x, 1, y);mesh.updateMatrix() // 更新投影矩阵,不更新各mesh位置会不正确boxModel.push(mesh.geometry.applyMatrix4(mesh.matrix));}}const boxGeometry = mergeGeometries(boxModel,true)let result = new THREE.Mesh(boxGeometry, this.boxMaterial)scene.add(result);console.log("執行完畢")} catch (error) {console.error('Error getting image pixels:', error);}};},

最终得到一副比较虚幻的图片

因为每个模型之间距离比较远,所以图片比较阴暗和虚幻,为了提高图片效果,可以将模型的宽和高改为5,

let geometry = new THREE.BoxGeometry(5, 5, 5);

这样就真实点了,可以根据电脑性能来调整去选取的像素点个数,如果电脑足够好,也可以根据上一篇音乐的效果,给这个图片添加音乐效果的跳动。

完整代码如下:

<template><div style="width:100px;height:100px;"><div id="container"></div></div>
</template><script>
import * as THREE from 'three'
import {OrbitControls} from "three/addons/controls/OrbitControls";
import {mergeGeometries} from "three/addons/utils/BufferGeometryUtils";let scene;
export default {name: "agv-single",data() {return{camera:null,cameraCurve:null,renderer:null,container:null,controls:null,imageData:[],boxMaterial:[],}},methods:{initScene(){scene = new THREE.Scene();},initCamera(){this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);this.camera.position.set(200,400,200);},initLight(){//添加两个平行光const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);directionalLight1.position.set(300,300,600)scene.add(directionalLight1);const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);directionalLight2.position.set(600,200,600)scene.add(directionalLight2);},initBox(){const img = new Image();img.src = '/static/images/image.jpg';let geometry = new THREE.BoxGeometry(5, 5, 5);img.onload = async () => {let boxModel = []try {const allPixels = await this.getImagePixels(img);for (let i = 0; i < allPixels.length; i++) {if(i%40 === 0) {let r = allPixels[i].r;let g = allPixels[i].g;let b = allPixels[i].b;let x = allPixels[i].x;let y = allPixels[i].y;let cubeMaterial = new THREE.MeshPhysicalMaterial({color: 'rgb(' + r + ', ' + g + ', ' + b + ')'});this.boxMaterial.push(cubeMaterial)let mesh = new THREE.Mesh(geometry.clone(), cubeMaterial);mesh.position.set(x, 1, y);mesh.updateMatrix() // 更新投影矩阵,不更新各mesh位置会不正确boxModel.push(mesh.geometry.applyMatrix4(mesh.matrix));}}const boxGeometry = mergeGeometries(boxModel,true)let result = new THREE.Mesh(boxGeometry, this.boxMaterial)scene.add(result);console.log("執行完畢")} catch (error) {console.error('Error getting image pixels:', error);}};},getImagePixels(image) {return new Promise((resolve) => {const canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');canvas.width = image.width;canvas.height = image.height;ctx.drawImage(image, 0, 0);const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);const data = imageData.data;const pixels = [];for (let i = 0; i < data.length; i += 4) {const x = (i / 4) % canvas.width;const y = Math.floor((i / 4) / canvas.width);const r = data[i];const g = data[i + 1];const b = data[i + 2];const a = data[i + 3];pixels.push({ x, y, r, g, b, a });}resolve(pixels); // 返回所有像素的数据数组});},initRenderer(){this.renderer = new THREE.WebGLRenderer({ antialias: true });this.container = document.getElementById("container")this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);this.renderer.setClearColor('#AAAAAA', 1.0);this.container.appendChild(this.renderer.domElement);},initControl(){this.controls = new OrbitControls(this.camera, this.renderer.domElement);this.controls.enableDamping = true;this.controls.maxPolarAngle = Math.PI / 2.2;      // // 最大角度},initAnimate() {requestAnimationFrame(this.initAnimate);this.renderer.render(scene, this.camera);},initPage(){this.initScene();this.initCamera();this.initLight();this.initBox();this.initRenderer();this.initControl();this.initAnimate();}},mounted() {this.initPage()}
}
</script><style scoped>
#container{position: absolute;width:100%;height:100%;overflow: hidden;
}</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/741859.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Oracle DBMS_LOCK

DBMS_lock是Oracle数据库中的一个包&#xff0c;主要用于控制并发和实现用户锁。在PL/SQL代码块中&#xff0c;有些操作代码块不能被多个会话同时进行执行&#xff0c;例如生成中间数据表等。如果此部分代码块被另个会话调用&#xff0c;则会造成中间数据表的数据在同一个会话中…

代码随想录算法训练营第七天|454. 四数相加 II

454. 四数相加 II 已解答 中等 相关标签 相关企业 给你四个整数数组 nums1、nums2、nums3 和 nums4 &#xff0c;数组长度都是 n &#xff0c;请你计算有多少个元组 (i, j, k, l) 能满足&#xff1a; 0 < i, j, k, l < nnums1[i] nums2[j] nums3[k] nums4[l] 0 示例 …

互联网行业的应届大学生,如何制作高水平简历?

雇主通常只会花大约25秒的时间浏览一份简历,因此,拥有一份出色的简历对于找到理想工作至关重要。如果您的简历没有令人印象深刻的特点,那么如何才能在竞争激烈的求职市场中脱颖而出呢? 如果您不知道如何在简历上有效地展示自己,或者觉得简历无论怎么修改都不够突出,那么请…

安装、配置MySQL

安装相关软件 MySQL Server、MySQL Workbench MySQL Server&#xff1a;专门用来提供数据存储和服务的软件 MySQL Workbench&#xff1a;可视化的 MySQL 管理工具 官网安装 https://www.mysql.com/ 官网 MySQL :: Download MySQL Installer 安装包路径 在这里选择版本和和对应…

多图如何导入多个二维码?图片批量导出二维码的技巧

多个图片分别生成对应的二维码怎么做&#xff1f;现在扫码看图片是一种很常用的内容预览方式&#xff0c;有些产品包装也会采用这种方式来展示对应的信息&#xff0c;怎么简单快速的将图片生成二维码&#xff0c;相信有很多的小伙伴都非常的感兴趣。那么小编通过下面这篇文章来…

力扣-28. 找出字符串中第一个匹配项的下标(内置函数或双指针)

找出字符串中第一个匹配项的下标 给你两个字符串 haystack 和 needle &#xff0c;请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标&#xff08;下标从 0 开始&#xff09;。如果 needle 不是 haystack 的一部分&#xff0c;则返回 -1 。 示例 1&#xff1a; …

分布式微服务 - 3.服务调用 - 1.概念

分布式微服务 - 3.服务调用 - 1.概念 项目示例&#xff1a; 无 内容提要&#xff1a; 服务调用、负载均衡、框架降级熔断限流、框架网关、框架 文档&#xff1a; 无 服务调用 服务调用时&#xff0c;需要先获取服务消费者的ip和端口号等信息。因此&#xff0c;一般服务…

常见的特殊端口号及其用途

21端口&#xff1a;FTP&#xff08;文件传输协议&#xff09;服务端口。FTP允许用户进行文件传输&#xff0c;如上传和下载文件。22端口&#xff1a;SSH&#xff08;安全外壳协议&#xff09;服务端口。SSH用于远程登录到服务器&#xff0c;并提供加密的数据传输。23端口&#…

探索C++中的动态数组:实现自己的Vector容器

&#x1f389;个人名片&#xff1a; &#x1f43c;作者简介&#xff1a;一名乐于分享在学习道路上收获的大二在校生 &#x1f648;个人主页&#x1f389;&#xff1a;GOTXX &#x1f43c;个人WeChat&#xff1a;ILXOXVJE &#x1f43c;本文由GOTXX原创&#xff0c;首发CSDN&…

Python 装饰器decorator 圣经

文章目录 普通装饰器decorator0. 万能公式&#xff0c;非常重要1. 便于入门的decorator原理2. 理解函数3. 装饰器的作用:4. 装饰器的语法糖5. 装饰器顺序6. 极简的装饰器7. 装饰器的参数无参 函数装饰器有参 函数装饰器 类装饰器class decorator0. 万能公式&#xff0c;非常重要…

判断一个整数是不是2的阶次方

boolean check(){int sum 50;boolean flag true;while(sum > 1){if (sum % 2 0){sum sum % 2;}else {flag false;break;}}return flag;}

uView ScrollList 横向滚动列表

该组件一般用于同时展示多个商品、分类的场景&#xff0c;也可以完成左右滑动的列表。 #平台差异说明 App&#xff08;vue&#xff09;App&#xff08;nvue&#xff09;H5小程序√√√√ #基本使用 通过slot传入内容 <template><u-scroll-list><view v-for…

echarts line绘制机组开关状态折线图

2024.3.12今天我学习了如何用echarts line实现设备开关状态的效果。 代码如下&#xff1a; option {xAxis: {type: time,},yAxis: {type: value,splitNumber:2,// axisLine: {// show: true,// lineStyle: {// color:#808080// }// },axisLabel:{formatt…

管控员工上网行为(让老板管理更省心更高效)

很多老板都有这样一种顾虑&#xff1a; 员工到底有没有认真工作&#xff0c;工作是不是做到了全身心投入。 为什么会有担心员工工作状态的问题发生&#xff1f; 无疑是员工在上班时间浏览与工作无关的网站、下载私人文件、甚至是泄露公司机密等行为&#xff0c;让老板不放心了…

Elasticsearch:在本地使用 Gemma LLM 对私人数据进行问答

在本笔记本中&#xff0c;我们的目标是利用 Google 的 Gemma 模型开发 RAG 系统。 我们将使用 Elastic 的 ELSER 模型生成向量并将其存储在 Elasticsearch 中。 此外&#xff0c;我们将探索语义检索技术&#xff0c;并将最热门的搜索结果作为 Gemma 模型的上下文窗口呈现。 此外…

【Python】探索PyPinyin 库:Python 中的中文拼音转换工具

花未全开月未圆&#xff0c; 半山微醉尽余欢。 何须多虑盈亏事&#xff0c; 终是小满胜万全。 —— 《对抗路—吕布》 PyPinyin 是一个功能强大的 Python 库&#xff0c;用于将中文文本转换为拼音。它提供了丰富的功能&#xff0c;能够满足各种中文文本处理的需求。在本文中&am…

岭回归:优化预测的利器

在数据科学和机器学习的领域&#xff0c;构建准确、稳定的预测模型是一项至关重要的任务。岭回归作为一种强大的工具&#xff0c;被设计用来应对数据集中存在多重共线性的问题&#xff0c;并通过引入正则化来缩小预测误差。 1. 岭回归的原理&#xff1a; 岭回归是线性回归的一…

js使用canvas实现图片鼠标滚轮放大缩小拖拽预览

html代码 todo 实现画矩形框&#xff0c;圆形roi <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta name"viewport" content"widthdevice-width, initial-scale1.0"> <title&…

【国产】API接口管理平台的产品设计与搭建讲解

【国产接口管理平台】PhalApi Pro (π框架专业版) PhalApi Pro (发音&#xff1a;π框架专业版)&#xff0c;是一款国产企业级API接口管理平台&#xff0c;可以零代码、快速搭建API接口开发平台、接口开放平台、接口管理平台。基于PhalApi开源接口开发框架&#xff0c;通过低代…

在java的类中即可以有main方法也可以没有main方法

原理: 在Java中&#xff0c;一个类可以没有main方法。main方法是Java程序的入口点&#xff0c;它是程序执行的起始点。如果一个类没有main方法&#xff0c;那么该类无法直接作为可执行程序运行。 然而&#xff0c;一个Java程序可以包含多个类&#xff0c;其中只需要一个类包含…