ZBLOG

能否基于three.js 编写一个可以改变图片局部颜色的例子

当然可以!以下是一个基于 Three.js 的示例,演示如何改变图片的局部颜色。在这个例子中,我们将使用一个平面(Plane)上的纹理,并在某些区域改变其颜色。

  1. // 引入Three.js库
  2. import * as THREE from 'three';
  3. // 创建场景、相机和渲染器
  4. const scene = new THREE.Scene();
  5. const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  6. const renderer = new THREE.WebGLRenderer({ antialias: true });
  7. renderer.setSize(window.innerWidth, window.innerHeight);
  8. document.body.appendChild(renderer.domElement);
  9. // 创建平面几何体并加载纹理
  10. const geometry = new THREE.PlaneGeometry(5, 5);
  11. const textureLoader = new THREE.TextureLoader();
  12. const texture = textureLoader.load('path/to/your/image.jpg'); // 替换为你的图片路径
  13. // 创建材质,并设置纹理
  14. const material = new THREE.MeshBasicMaterial({ map: texture });
  15. const plane = new THREE.Mesh(geometry, material);
  16. scene.add(plane);
  17. // 设置相机位置
  18. camera.position.z = 5;
  19. // 准备要改变颜色的区域
  20. function changeColor(x, y) {
  21. const canvas = document.createElement('canvas');
  22. const context = canvas.getContext('2d');
  23. // 将原始纹理绘制到canvas上以便处理像素数据
  24. context.drawImage(texture.image, 0, 0);
  25. const width = texture.image.width;
  26. const height = texture.image.height;
  27. // 获取像素数据
  28. const pixelData = context.getImageData(0, 0, width, height);
  29. // 改变指定位置的颜色 (这里以x,y为中心点)
  30. for (let i = -10; i <= 10; i++) { // 改变范围可调整
  31. for (let j = -10; j <= 10; j++) {
  32. const pxIndex = ((y + j) * width + (x + i)) * 4;
  33. if (pxIndex >= 0 && pxIndex < pixelData.data.length) {
  34. pixelData.data[pxIndex] = 255; // Red channel
  35. pixelData.data[pxIndex+1] = 0; // Green channel
  36. pixelData.data[pxIndex+2] = 0; // Blue channel
  37. }
  38. }
  39. }
  40. context.putImageData(pixelData, 0, 0);
  41. // 更新纹理以应用变化
  42. material.map.needsUpdate = true;
  43. }
  44. // 渲染循环
  45. function animate() {
  46. requestAnimationFrame(animate);
  47. renderer.render(scene, camera);
  48. }
  49. animate();
  50. // 添加鼠标点击事件来改变颜色局部区域
  51. window.addEventListener('click', (event) => {
  52. // 获取鼠标在画布中的坐标并转换为纹理坐标系统
  53. const mouseX = ((event.clientX / window.innerWidth) * 2 - 1) * (texture.image.width / texture.image.height);
  54. const mouseY = -((event.clientY / window.innerHeight) * 2 - 1);
  55. changeColor(Math.floor(mouseX), Math.floor(mouseY));
  56. });

注意事项:

  • 请确保将 'path/to/your/image.jpg' 替换为你实际的图像路径。
  • 上述代码实现了基本的功能,当你点击画布时,指定位置附近会被改为红色。你可以根据需要修改 changeColor 函数内的逻辑,以适应不同的需求。
  • 确保项目中已引入 Three.js 库,可以通过 npm 安装或直接引入 CDN 链接。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21278

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?