首页 > 代码库 > canvas——七巧板

canvas——七巧板

技术分享

<canvas id="canvas" style="border:1px solid #aaa;display: block;margin: auto;"></canvas>

    <script type="text/javascript">

    var tangram = [
        {p:[{x:0,y:0},{x:300,y:300},{x:0,y:600}],color:"#caff67"},
        {p:[{x:0,y:0},{x:300,y:300},{x:600,y:0}],color:"#67becf"},
        {p:[{x:300,y:600},{x:150,y:450},{x:0,y:600}],color:"#ef3d61"},
        {p:[{x:300,y:600},{x:600,y:300},{x:600,y:600}],color:"#f9f51a"},
        {p:[{x:300,y:300},{x:450,y:450},{x:300,y:600},{x:150,y:450}],color:"#a594c0"},
        {p:[{x:300,y:300},{x:450,y:150},{x:450,y:450}],color:"#fa8ece"},
        {p:[{x:450,y:150},{x:600,y:0},{x:600,y:300},{x:450,y:450}],color:"#f6ca29"},

    ]
        window.onload = function(){
            var canvas = document.getElementById("canvas");

            canvas.width = 600;
            canvas.height = 600;
    
            var context = canvas.getContext("2d");

            for (var i = 0; i < tangram.length; i++) {
                draw(tangram[i],context)
            }

            function draw(piece, cxt){
                cxt.beginPath();
                cxt.moveTo(piece.p[0].x,piece.p[0].y);
                for (var i = 1; i < piece.p.length; i++) {
                    cxt.lineTo(piece.p[i].x,piece.p[i].y);
                }
                cxt.fillStyle = piece.color;
                cxt.closePath();
                
                cxt.fill();
            }
        }
    </script>

 

canvas——七巧板