小遊戲中使用 canvas內容作紋理

因爲小遊戲中沒法使用html元素,開發中須要展現用戶信息時,只有兩個選擇:javascript

1-使用threejs加載字體模型,但中文字體模型都超過10MB。

2-使用2d canvas畫布做爲threejs幾何體的材質,該方法自由靈活,無需額外字體,也是目前小遊戲開發中最佳實踐。

---注,該threejs爲修改版,以適配小遊戲。
---連接:https://gist.github.com/WangS...html

import './js/libs/weapp-adapter'
import * as THREE from './js/libs/three.js'

let info, Performance, width, height, size, canvas2d, ctx, camera, scene, renderer, geometry, texture, mesh

wx.getSystemInfo({
    success(res) {
        info = res
        info.aspectRatio = (info.screenWidth / info.screenHeight)
        Performance = wx.getPerformance()
        run()
    }
})

function run() {
    width = window.innerWidth
    height = window.innerHeight / 2;
    size = 128;
    canvas2d = wx.createCanvas()
    ctx = canvas2d.getContext('2d');

    init();
    animate();
}

function changeCanvas() {
    ctx.font = '16pt Arial';
    ctx.fillStyle = 'blue';
    ctx.fillRect(0, 0, canvas2d.width, canvas2d.height);
    ctx.fillStyle = 'white';
    ctx.fillRect(10, 10, canvas2d.width - 20, canvas2d.height - 20);
    ctx.fillStyle = 'black';
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText("王樹賢", canvas2d.width / 2, canvas2d.height / 2);
}

function init() {
    renderer = new THREE.WebGLRenderer({
        antialias: true,
        canvas: canvas,
    });
    renderer.setSize(width, height);

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
    camera.position.z = 500;
    scene.add(camera);

    texture = new THREE.Texture(canvas2d);
    let material = new THREE.MeshBasicMaterial({
        map: texture
    });
    geometry = new THREE.BoxGeometry(200, 200, 200);
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    canvas2d.width = canvas2d.height = size;
}

function animate() {
    requestAnimationFrame(animate);

    changeCanvas();
    texture.needsUpdate = true;
    mesh.rotation.y += 0.01;
    renderer.render(scene, camera);
}

圖片描述

相關文章
相關標籤/搜索