美文网首页程序员
canvas绘制七巧板

canvas绘制七巧板

作者: 周紫一 | 来源:发表于2018-04-20 23:25 被阅读20次

效果:

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>

相关文章

网友评论

    本文标题:canvas绘制七巧板

    本文链接:https://www.haomeiwen.com/subject/uektlftx.html