我试图在THREE.js场景中创建现有svg元素的副本。我使用this example将svg转换为图像,然后根据图像创建一个带纹理的平面并将其添加到场景中。但是,这架飞机是黑色的。如果我使用纯色而不是纹理,它会被正确渲染,那么我的纹理就会出现问题。
var legend = document.querySelector("svg.ViewLegend");
var svgData = new XMLSerializer().serializeToString(legend);
var canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 64;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(svgData));
img.onload = function () {
ctx.drawImage(img, 0, 0);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
var material = new THREE.MeshBasicMaterial({
map: texture,
});
material.map.minFilter = THREE.LinearFilter;
//If I use the material below, it works correctly
//var material = new THREE.MeshPhongMaterial({color: 0xCC0000});
var geometry = new THREE.PlaneBufferGeometry(512, 64, 1, 1);
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
};
答案 0 :(得分:4)
我相信你需要这样做:
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(svgData))) );
img.onload = function() {
ctx.drawImage(img, 0, 0);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
var geometry = new THREE.SphereGeometry(3, 50, 50, 0, Math.PI * 2, 0, Math.PI * 2);
var material = new THREE.MeshBasicMaterial({ map: texture });
material.map.minFilter = THREE.LinearFilter;
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
};