开发笔记:使用canvas实现3D金字塔比例图表📈
业务中展现如下:
在线示例
代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.canvas-warpper {
position: relative;
width: 800px;
height: 800px;
}
.canvas {
position: absolute;
width: 400px;
height: 400px;
left: 0;
top: 0;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="canvas-warpper">
<canvas id="canvas1" class="canvas" ></canvas>
</div>
</body>
</html>
<script type="text/javascript">
window.onload = function(){
var canvas1 = document.getElementById("canvas1");
var context = canvas1.getContext("2d");
var x = 28;
var y = 32;
var z = 40;
var radian = (2 * Math.PI / 360) * 30;
canvas1.width = 400;
canvas1.height = 400;
context.beginPath();
var maxH = 200 /Math.tan(radian);
context.moveTo(0, maxH);
context.lineTo(200,400);
context.lineTo(400,maxH);
context.lineTo(200,0);
context.lineTo(0, maxH);
context.moveTo(200, 400);
context.lineTo(200, 0);
context.fillStyle = "#0289F2";
context.fill();
context.closePath();
// 100份中每份斜边长(勾股定理求的)
var itemHypotenuseH = Math.sqrt(200*200 + maxH * maxH)/100;
// 100份中每份主轴长
var itemAxisH = 400 / 100;
// 100份中每份直角边竖边长
var itemH = maxH / 100;
// 100份中每份直角边横边长
var itemW = Math.sqrt((itemHypotenuseH)*(itemHypotenuseH) - itemH*itemH);
context.beginPath();
context.moveTo(200,itemAxisH*(x+y)+(400-itemAxisH*(x+y))/2);
context.lineTo(400,itemAxisH*(x+y)+(400-itemAxisH*(x+y))/2);
context.lineWidth = 1;
context.strokeStyle = "#000";
context.stroke();
context.closePath();
context.beginPath();
context.moveTo(200-itemW*x,itemH*x);
context.lineTo(200,itemAxisH*x);
context.lineTo(200+itemW*x,itemH*x);
context.lineTo(200,0);
console.log(itemHypotenuseH*x);
context.fillStyle = "#FDC501";
context.fill();
context.closePath();
// 画描述线 80以上
context.beginPath();
context.moveTo(200,itemAxisH*(x/2));
context.lineTo(400,itemAxisH*(x/2));
context.lineWidth = 1;
context.strokeStyle = "#000";
context.stroke();
context.closePath();
context.beginPath();
context.moveTo(200-itemW*(x+y),itemH*(x+y));
context.lineTo(200,itemAxisH*(x+y));
context.lineTo(200+itemW*(x+y),itemH*(x+y));
context.lineTo(200+itemW*x,itemH*x);
context.lineTo(200,itemAxisH*x);
context.lineTo(200-itemW*x,itemH*x);
context.fillStyle = "#1FFE8D";
context.fill();
context.closePath();
// 画描述线 70~80 13559
context.beginPath();
context.moveTo(200,itemAxisH*(x+y/2));
context.lineTo(0,itemAxisH*(x+y/2));
context.lineWidth = 1;
context.strokeStyle = "#000";
context.stroke();
context.closePath();
context.beginPath();
context.moveTo(200,0);
context.lineTo(200,400);
context.lineWidth = 1;
context.strokeStyle = "rgba(45,71,86,0.4)";
context.stroke();
context.closePath();
}
</script>