前端绘制立体效果的三角形的demo在移动端使用时,需要自适应屏幕。canvas上无法设置rem,所以在canvas外加一个父级元素设置为rem,再将canvas的宽高设置为100% 100%。如果想出现立体效果,应该将一个三角形分为三个三角形来进行绘制。突出立体的效果,应该设置过渡色。 toTriangle(a,b,c){//a为左边三角的长度,b为顶点距离中心的长度,c为右边顶点距离中心的长度var bg = document.getElementById(‘circle_triangle’);var ctx = bg.getContext(‘2d’); //自适应cavas画布的宽高,动态设置。let canvas_outer = document.getElementById(‘outer’);console.log(canvas_outer.offsetHeight);bg.height = canvas_outer.offsetHeight;bg.width = canvas_outer.offsetWidth; let bod = bg.getBoundingClientRect()let wid = bod.width;//三角形三个顶点从顶点:a_dot,左边点:b_dot,右边点:c_dot。和参数a,b,c有区别let a_dot = [wid/2,(wid/2)*(1-b)]let b_dot = [(wid/2)*(1-a*Math.cos((Math.PI)*45/180)),(wid/2)*(a*Math.sin((Math.PI)*45/180)+1)]let c_dot = [(wid/2)*(1+c*Math.cos((Math.PI)*45/180)),(wid/2)*(c*Math.sin((Math.PI)*45/180)+1)] //绘制三角形1(左边)ctx.beginPath();ctx.moveTo(wid/2,wid/2); //从A开始ctx.lineTo(b_dot[0],b_dot[1])//ctx.lineTo(a_dot[0],a_dot[1])var grd1 = ctx.createLinearGradient(b_dot[0],b_dot[1],a_dot[0],a_dot[1],);//使用渐变颜色填充,从 点b到agrd1.addColorStop(0,”#”); //起始颜色grd1.addColorStop(0.25,”#”); //起始颜色grd1.addColorStop(0.5,”#”); //起始颜色grd1.addColorStop(0.75,”#”); //终点颜色grd1.addColorStop(1,”#”); //终点颜色ctx.fillStyle=grd1; //以上面定义的渐变填充ctx.fill(); //闭合形状并且以填充方式绘制出来ctx.closePath() //绘制三角形2(右边)ctx.beginPath();ctx.moveTo(wid/2,wid/2); //从A开始ctx.lineTo(a_dot[0],a_dot[1])ctx.lineTo(c_dot[0],c_dot[1])var grd2 = ctx.createLinearGradient(a_dot[0],a_dot[1],c_dot[0],c_dot[1]);//使用渐变颜色填充,从(0,0)到(200,0) (左到右)grd2.addColorStop(0,”#”); //起始颜色grd2.addColorStop(0.25,”#”); //起始颜色grd2.addColorStop(0.5,”#”); //起始颜色grd2.addColorStop(0.75,”#”); //终点颜色grd2.addColorStop(1,”#”); //终点颜色ctx.fillStyle=grd2; //以上面定义的渐变填充ctx.fill(); //闭合形状并且以填充方式绘制出来ctx.closePath() //绘制三角形3(底部)ctx.beginPath();ctx.moveTo(wid/2,wid/2); //从A开始ctx.lineTo(b_dot[0],b_dot[1])//ctx.lineTo(c_dot[0],c_dot[1]);var grd3 = ctx.createLinearGradient(b_dot[0],b_dot[1],c_dot[0],c_dot[1]);//使用渐变颜色填充,从(0,0)到(200,0) (左到右)grd3.addColorStop(0,”#”); //起始颜色grd3.addColorStop(0.25,”#”); //起始颜色grd3.addColorStop(0.5,”#”); //起始颜色grd3.addColorStop(0.75,”#”); //终点颜色grd3.addColorStop(1,”#”); //终点颜色ctx.fillStyle=grd3; //以上面定义的渐变填充ctx.fill(); //闭合形状并且以填充方式绘制出来ctx.closePath()}