threejs不仅支持各种texture的导入生成贴图,还可以利用canvas绘制图片作为贴图。这就用到了CanvasTexture,它接受一个canas对象。只要我们绘制好canvas,就可以作为贴图了。这里我们利用一张图片来实现这个效果。
基础代码:
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as Dat from "dat.gui";
// 导入Three.js库
// import * as THREE from "three";
// 创建场景、相机、渲染器等
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const control = new OrbitControls(camera, renderer.domElement);
// 创建立方体的几何体
const geometry = new THREE.BoxGeometry(3, 3, 3);
// 创建动态Canvas并在其中绘制图像
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 512;
const context = canvas.getContext("2d");
const image = new Image();
image.src = "src/assets/css.jpg"; // 替换为你的图片路径
image.onload = function() {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
// 将Canvas创建为贴图
const texture = new THREE.CanvasTexture(canvas);
// 创建贴图材质
const materials = [
new THREE.MeshBasicMaterial({ color: "#f90" }),
new THREE.MeshBasicMaterial({ map: texture }),
new THREE.MeshBasicMaterial({ color: "#63a" }),
new THREE.MeshBasicMaterial({ color: "#e2d" }),
new THREE.MeshBasicMaterial({ color: "#c57" }),
new THREE.MeshBasicMaterial({ color: "#f00" })
];
// 创建几何体网格对象
const cube = new THREE.Mesh(geometry, materials);
// 将网格对象添加到场景中
scene.add(cube);
};
// 设置相机位置
camera.position.z = 5;
// 渲染场景
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
最后的展示效果如下:
文章来源:https://www.toymoban.com/news/detail-673135.html
这里特别要注意贴图异步问题。在我们通过drawImage绘制图片的时候,sence.add(cube)这个操作要在img.onload()中执行,否则图片会无法展示出来文章来源地址https://www.toymoban.com/news/detail-673135.html
到了这里,关于threejs贴图系列(一)canvas贴图的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!