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

Canvas学习记录绘制七巧板(01)

程序员文章站 2022-03-03 11:21:12
...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        #canvas {
            border: 1px solid #000;
            display: block;
            margin: 50px auto
        }
    </style>
</head>
<body>

<canvas id="canvas">
    您的浏览器不支持 HTML5 canvas 标签,换个浏览器试试.
</canvas>

<script>
    window.onload = () => {
        //获取canvas标签
        var canvas = document.getElementById('canvas');

        canvas.width = 800; //设置canvas宽度
        canvas.height = 800;//设置canvas高度
        //获取canvas上下文内容
        var context = canvas.getContext('2d');

        //每个点坐标值集合
        let params = [
            {path: [{x: 100, y: 100}, {x: 400, y: 100}, {x: 250, y: 250}], color: "#fe665b"},
            {path: [{x: 100, y: 100}, {x: 100, y: 400}, {x: 250, y: 250}], color: "#03a697"},
            {path: [{x: 400, y: 100}, {x: 325, y: 175}, {x: 325, y: 325}, {x: 400, y: 250}], color: "#ec3c60"},
            {path: [{x: 400, y: 250}, {x: 250, y: 400}, {x: 400, y: 400}], color: "#f6ca2d"},
            {path: [{x: 250, y: 250}, {x: 325, y: 325}, {x: 325, y: 175}], color: "#f6f020"},
            {path: [{x: 100, y: 400}, {x: 250, y: 400}, {x: 175, y: 325}], color: "#f094c5"},
            {path: [{x: 250, y: 250}, {x: 175, y: 325}, {x: 250, y: 400}, {x: 325, y: 325}], color: "#a796c2"},
        ];
        //遍历最外层
        for (let i = 0; i < params.length; i++) {
            draw(params[i], context);
        }

    }

    function draw(data, cxt) {

        cxt.beginPath(); //开始绘制

        cxt.moveTo(data.path[0].x, data.path[0].y);//移动画笔

        for (let j = 0; j < data.path.length; j++) {
            cxt.lineTo(data.path[j].x, data.path[j].y); //添加一个新的坐标点 (该方法并不会创建线条)
            cxt.fillStyle = data.color; //设置图形填充的颜色

        }
        cxt.closePath();//结束绘制  //保存每一个图形的状态
        cxt.fill(); //设置样式为填充模式

        cxt.strokeStyle = '#000'; //设置线条颜色
        cxt.lineWidth = 2;//设置线条宽度
        cxt.stroke(); //方法会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径
    }
</script>
</body>
</html>

效果图:
Canvas学习记录绘制七巧板(01)

相关标签: canvas canvas js