Threejs not only supports the import of various textures to generate textures, but can also use canvas to draw pictures as textures. This uses CanvasTexture, which accepts a canas object. As long as we draw the canvas, it can be used as a texture. Here we use a picture to achieve this effect.
Basic code:
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();
The final display effect is as follows:
Special attention should be paid here to the problem of texture asynchronousness. When we draw a picture through drawImage, the operation of scene.add(cube) must be performed in img.onload(), otherwise the picture will not be displayed.