利用HTML5绘制点线面组成的3D图形的示例

2019-01-28 16:22:13王冬梅


  然后是面对象:

  面对象的属性页很容易理解,一个面就是一个正方形 , v1v2v3v4是面的四个顶点,zIndex这个属性很重要,是代表这个面的层级,是在最外面还是在里面,这个必须要有,这样当用canvas画的时候才能让这个面画在最前面,才不会被其他的面遮盖。zIndex的值也很容易理解,就是顶点z轴坐标的平均值,其实也就是中心点的z轴坐标。颜色就是这个面的颜色啦。

XML/HTML Code复制内容到剪贴板
  1. var Face = function(vector1,vector2,vector3,vector4,color){                this.v1 = vector1;   
  2.             this.v2 = vector2;                this.v3 = vector3;   
  3.             this.v4 = vector4;                this.color = color;   
  4.             this.zIndex = (this.v1.z + this.v2.z + this.v3.z + this.v4.z)/4;                this.draw = function(){   
  5.                 ctx.save();                    ctx.beginPath();   
  6.                 ctx.moveTo(this.v1._get2d().x , this.v1._get2d().y);                    ctx.lineTo(this.v2._get2d().x , this.v2._get2d().y);   
  7.                 ctx.lineTo(this.v3._get2d().x , this.v3._get2d().y);                    ctx.lineTo(this.v4._get2d().x , this.v4._get2d().y);   
  8.                 ctx.closePath();                    // ctx.fillStyle = "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+",0.2)";