您的位置:首页 > 其它

如何实现TWaver 3D颜色渐变

2014-10-21 13:39 274 查看
一般而言,需要实现3D物体的渐变,通常的思路就是通过2D绘制一张渐变canvas图片作为3D对象的贴图,这种方式是可以解决这类问题的,不过对于一般用户而言,通过2D生成一张渐变的图片,有一定的难度,另外如果要生成的图片比较多,性能效率上会成为一个瓶颈,特别是渐变随着条件在不断变化的情况下,就需要每次绘制的时候都去生成一张渐变的canvas图,效率极其低。

在3D中,另外一种通常的方式就是通过顶点色来实现渐变,然而这种方式对于用户的难度更大,因为需要用户了解3D底层的一些原理,同时需要对于每个物体的顶点结构有深入了解;尽管如此难,这种方式由于受到了顶点数量的限制,其渐变的颜色数量也受到了限制,这是不能接受的一个问题。

由此看来,3D对象实现任意渐变有一定难度。不过,有一个好消息是,对于使用TWaver 3D的用户而言,TWaver 3D从底层封装了一些常用的渐变,用户只需要调用简单的接口,就可以实现3D物体的色彩缤纷。
如果通过TWaver 3D实现渐变,通过一个简单的例子,就可以看出来效果:

var box, node;
function load() {

box = new mono.DataBox();
var camera = new mono.PerspectiveCamera(30, 1.5, 0.1, 10000);
camera.setPosition(0, 200, 500);

var network = new mono.Network3D(box, camera, myCanvas);
var interaction = new mono.DefaultInteraction(network);
interaction.zoomSpeed = 10;
network.setInteractions([new mono.SelectionInteraction(network), interaction]);
mono.Utils.autoAdjustNetworkBounds(network, document.documentElement, 'clientWidth', 'clientHeight', 0, 30);

var pointLight = new mono.PointLight(0xFFFFFF, 1);
pointLight.setPosition(10000, 10000, 10000);
box.add(pointLight);
box.add(new mono.AmbientLight(0x888888));
createGradientNode();
}

function createGradientNode(i) {
var node = new mono.Cylinder(30, 30, 60,100);
node.setStyle('m.color', 'orange');
node.setStyle('side.m.gradient', {
0 : 'red',
1 : 'orange'
});
node.setStyle('top.m.gradient', {
0 : 'yellow',
1 : 'orange'
});
node.setStyle('bottom.m.gradient', {
0 : 'yellow',
1 : 'red'
});
node.setStyle('side.m.gradientType', 2);
node.setStyle('top.m.gradientType', 5);
node.setStyle('bottom.m.gradientType', 5);
box.add(node);
}

function randomSeverity() {
var severities = mono.AlarmSeverity.severities;
return severities.get(randomInt(severities.size()));
};

function randomInt(n) {
return Math.floor(Math.random() * n);
};


其中设置节点渐变的代码如下,其中对圆柱体的top,side,bottom 3个面都设置了渐变,top,bottom设置了radial 渐变,side设置了linear渐变:

node.setStyle('side.m.gradient', {
0 : 'red',
1 : 'orange'
});
node.setStyle('top.m.gradient', {
0 : 'yellow',
1 : 'orange'
});
node.setStyle('bottom.m.gradient', {
0 : 'yellow',
1 : 'red'
});
node.setStyle('side.m.gradientType', 2);
node.setStyle('top.m.gradientType', 5);
node.setStyle('bottom.m.gradientType', 5);


最终的效果如下:



可以看出,使用TWaver 3D,只需要很少的代码,就能实现效果比较炫的渐变效果。
如果你对于底层的实现比较感兴趣,在此也可以顺便提一下,其实底层的实现是GPU通过物体的UV坐标来实现的渐变,以linear-v渐变方式为例,如果你设置了0的位置是color1 ‘red’,1 的位置是 color2 ‘orange’,那么在任何一个点A上,假定其UV坐标为u,v,其颜色就可以在GPU里面计算得到:

finalColor = (v - 0) * color2 + (1 - v) * color1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐