欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用Canvas画一个七巧板

程序员文章站 2022-03-03 11:21:24
...

今天刚开始学习canvas,就画了一个简易的七巧板。

<!DOCTYPE html>
<html>
<head>
    <title>七巧板</title>
</head>

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

<script>
//定义一个数组包含七个对象,每个对象里有图形的顶点坐标数组(p)和图形颜色(color)。
//*注意四边形及以上的点的坐标一定要按顺序。
    var pos = [
        {p:[{x:0,y:0},{x:600,y:0},{x:300,y:300}],color:"#ed811f"},
        {p:[{x:600,y:0},{x:600,y:600},{x:300,y:300}],color:"#69dce8"},
        {p:[{x:0,y:0},{x:0,y:300},{x:150,y:450},{x:150,y:150}],color:"#e500cd"},
        {p:[{x:150,y:150},{x:150,y:450},{x:300,y:300}],color:"#0140e5"},
        {p:[{x:300,y:300},{x:150,y:450},{x:300,y:600},{x:450,y:450}],color:"#00e4a5"},
        {p:[{x:450,y:450},{x:300,y:600},{x:600,y:600}],color:"#e9e500"},
        {p:[{x:0,y:300},{x:0,y:600},{x:300,y:600}],color:"#0ea00f"}
    ]
    window.onload = function(){
        var canvas = document.getElementById("canvas");

        canvas.width = 600; 
        canvas.height = 600;
        if(canvas.getContext("2d")){
            var context = canvas.getContext("2d");
            for(var i = 0; i < pos.length; i++){
                draw(pos[i],context)
            }
        }else{
            alert("当前浏览器不支持Canvas,请更换浏览器再试");
        }
    }
    function draw(piece, ctx){
        ctx.beginPath();
        ctx.moveTo(piece.p[0].x, piece.p[0].y);
        for(var i=1; i<piece.p.length; i++){
            ctx.lineTo(piece.p[i].x, piece.p[i].y);         
        }
        ctx.closePath();

        ctx.fillStyle = piece.color;
        ctx.fill();

        ctx.lineWidth = 3;
        ctx.strokeStyle = "black";
        ctx.stroke();
    }
</script>
</html>