ThreeJs 2d画布文本渲染内存问题

时间:2017-12-15 06:07:42

标签: javascript canvas memory three.js

我正在使用2D画布渲染渲染近200个文本。它需要更多内存,有没有办法重用canvas元素。以下是我的工作代码。

var goalCanvas = document.createElement('canvas');
goalCanvas.width = Math.pow(2, Math.round(Math.log(parseInt(name.length) * parseInt(58)) / Math.log(2)));
goalCanvas.height = 128;
var planeGeometry = new THREE.PlaneGeometry(parseInt(name.length) * parseInt(3), 8);
var featureContext = goalCanvas.getContext('2d');
featureContext.fillStyle = "#ffffff";
featureContext.font = "54px roboto_condensedregular";
featureContext.textAlign = "center";
featureContext.fillText(name, goalCanvas.width / 2, 42);
var goalTexture = new THREE.Texture(goalCanvas)
goalTexture.needsUpdate = true;
var goalMaterial = new THREE.MeshBasicMaterial({
    map: goalTexture
});
goalMaterial.transparent = true;
var goalNameMesh = new THREE.Mesh(
    planeGeometry,
    goalMaterial
);

1 个答案:

答案 0 :(得分:0)

创建新画布必须只发生一次,只运行实际添加文本的代码:

var planeGeometry = new THREE.PlaneGeometry(parseInt(name.length) * parseInt(3), 8);
goalCanvas.height = 128;
var featureContext = goalCanvas.getContext('2d');
featureContext.fillStyle = "#ffffff";
featureContext.font = "54px roboto_condensedregular";
featureContext.textAlign = "center";
featureContext.fillText(name, goalCanvas.width / 2, 42);
var goalTexture = new THREE.Texture(goalCanvas)
goalTexture.needsUpdate = true;
var goalMaterial = new THREE.MeshBasicMaterial({
    map: goalTexture
});
goalMaterial.transparent = true;
var goalNameMesh = new THREE.Mesh(
    planeGeometry,
    goalMaterial
);

如果你在一个函数中使用它,它应该是这样的:

function AddText(canvas,name)
{
    var planeGeometry = new THREE.PlaneGeometry(parseInt(name.length) * parseInt(3), 8);
    var featureContext = canvas.getContext('2d');
    featureContext.fillStyle = "#ffffff";
    featureContext.font = "54px roboto_condensedregular";
    featureContext.textAlign = "center";
    featureContext.fillText(name, canvas.width / 2, 42);
    var goalTexture = new THREE.Texture(canvas)
    goalTexture.needsUpdate = true;
    var goalMaterial = new THREE.MeshBasicMaterial({
        map: goalTexture
    });
    goalMaterial.transparent = true;
    var goalNameMesh = new THREE.Mesh(
        planeGeometry,
        goalMaterial
    );
    return {"goalNameMesh": goalNameMesh, "goalTexture": goalTexture, "goalMaterial":goalMaterial, "featureContext": featureContext};
}


var goalCanvas = document.createElement('canvas'); //this should only run once
goalCanvas.width = Math.pow(2, Math.round(Math.log(parseInt(name.length) * parseInt(58)) / Math.log(2)));//and this
goalCanvas.height = 128;//and this
var addedText = AddText(goalCanvas, name) //you can loop this line for each text that you want to add, and it will return an object with all the handles in it