效果:
![](https://img.haomeiwen.com/i2321455/6a185b0c755b013b.png)
image.png
代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#canvas{
/*background-color: red;*/
}
div{
height: 400px;
width: 400px;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height=400 width=400>
你的浏览不支持HTML5 canvas
</canvas>
</div>
<script>
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
var position = [
{
pos: [{x:0, y:0},{x:100, y:100},{x:0, y:200}],
color: "red"
},
{
pos: [{x:0, y:0},{x:400, y:0},{x:200, y:200}],
color: "orange"
},
{
pos: [{x:200, y:200},{x:400, y:0},{x:400, y:400}],
color: "yellow"
},
{
pos: [{x:400, y:400},{x:300, y:300},{x:200, y:400}],
color: "green"
},
{
pos: [{x:100, y:300},{x:200, y:400},{x:100, y:400}],
color: "blue"
},
{
pos: [{x:100, y:300},{x:200, y:400},{x:400, y:400}],
color: "cyan"
},
{
pos: [{x:0, y:200},{x:0, y:400},{x:100, y:400}],
color: "purple"
},
{
pos: [{x:100, y:100},{x:300, y:300},{x:200, y:400}, {x:100, y:300}],
color: "brown"
},
{
pos: [{x:100, y:100},{x:100, y:400},{x:0, y:200}],
color: "aqua"
}
]
for(i in position){
ctx.fillStyle = position[i].color;
drawTriangle(position[i].pos);
}
//绘制多边形
function drawTriangle (arr){
ctx.beginPath();
ctx.moveTo(arr[0].x, arr[0].y)
for(i in arr){
ctx.lineTo(arr[i].x, arr[i].y);
}
ctx.closePath();
ctx.fill();
}
}
</script>
</body>
</html>
网友评论