小游戏中使用 canvas内容做纹理

由于小游戏中无法使用html元素,开发中需要展示用户信息时,只有两个选择:

1-使用threejs加载字体模型,但中文字体模型都超过10MB。
2-使用2d canvas画布作为threejs几何体的材质,该方法自由灵活,无需额外字体,也是目前小游戏开发中最佳实践。

---注,该threejs为修改版,以适配小游戏。
---链接:https://gist.github.com/WangS...

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);
}

图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值