PIXI+THREE
使用 PIXI 和 THREE 將三維和二維渲染在同一個 canvas 下面
效果
思路
- 初始化 PIXI 的 Application, 作為 pixi 最重要的變數
const app = new PIXI.Application({
width: 800,
height: 600,
// 畫素
resolution: window.devicePixelRatio,
// 透明
transparent: true,
// 抗鋸齒
antialias: true,
});
- 建立 container 並加入到
app.stage
中 - 建立自己的 sprite, 也就是上圖 pixi 中標識的 圖片
- 將 pixi 建立的 canvas 加入到 body 中
- 建立 Three 相關變數, camera, scene, renderer, box, light
- 將相關變數設定好內容
- 新建 pixi 中的 sprite, 名為 sprite3D, 新建
PIXI.Texture
, source 為 three 中renderer.dom
- 在 animate 方法中 更新 texture
原始碼
import * as THREE from "three";
import * as PIXI from "pixi.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import img1 from "./img/img1.jpg";
window.PIXI = PIXI;
function init() {
const { container, app, sprite } = initPixi();
// 設定圖片位置
sprite.scale.set(0.5, 0.5);
sprite.position.set(200, 200);
const { scene, renderer, camera, orbitControls, box } = initThree(app);
// 設定三維盒子變數
const sprite3DTexture = PIXI.Texture.from(renderer.domElement);
const sprite3D = new PIXI.Sprite(sprite3DTexture);
sprite3D.width = 300;
sprite3D.height = 200;
sprite3D.position.set(50, 100);
container.addChild(sprite3D);
// 迴圈方法
function animate() {
requestAnimationFrame(animate);
sprite.rotation += 0.01;
// 更新 three 渲染的內容
sprite3DTexture.update();
box.rotation.x += 0.01;
box.rotation.y += 0.01;
orbitControls.update();
renderer.render(scene, camera);
}
animate();
}
function initPixi() {
const app = new PIXI.Application({
width: 800,
height: 600,
// 畫素
resolution: window.devicePixelRatio,
// 透明
transparent: true,
// 抗鋸齒
antialias: true,
});
const container = new PIXI.Container();
// stage 全域性內容
app.stage.addChild(container);
const spriteTexture = createdPixiTexture(img1);
const sprite = new PIXI.Sprite(spriteTexture);
container.addChild(sprite);
document.body.appendChild(app.view);
return { container, app, sprite };
}
function createdPixiTexture(url) {
return PIXI.Texture.from(url);
}
function initThree(app) {
const scene = new THREE.Scene();
// 環境光
scene.add(new THREE.AmbientLight(0xffffff, 0.8));
scene.add(new THREE.AxesHelper(100));
const pointLight = new THREE.PointLight(0xfd08aa, 1);
pointLight.position.set(100, 100, 100);
const renderer = new THREE.WebGLRenderer({
// 設定透明
alpha: true,
antialias: true,
});
// 設定 pixi 限定的尺寸
renderer.setSize(300, 200);
renderer.pixelRatio = window.devicePixelRatio;
const camera = new THREE.PerspectiveCamera(45, 300 / 200);
camera.position.set(200, 300, 200);
camera.lookAt(0, 0, 0);
const orbitControls = new OrbitControls(camera, app.view);
orbitControls.update();
const box = new THREE.Mesh(
new THREE.BoxBufferGeometry(40, 50, 60),
new THREE.MeshStandardMaterial({
color: 0xfea67a,
roughness: 2,
})
);
scene.add(box);
return { scene, camera, renderer, orbitControls, box };
}
init();