canvas绘制七巧板

在上一节中,我们了解了如何使用canvas绘制线段,这一节,我们使用canvas绘制七巧板。
html代码如下所示,和第一节中代码一致:




    
    Canvas绘制七巧板




    当用户浏览器不支持Canvas,请更换浏览器重试!



直接上代码,js代码如下所示:

var tangram = [
    {p: [{x: 0, y: 0}, {x: 800, y: 0}, {x: 400, y: 400}], color: "#caff67"},
    {p: [{x: 0, y: 0}, {x: 400, y: 400}, {x: 0, y: 800}], color: "#67becf"},
    {p: [{x: 800, y: 0}, {x: 800, y: 400}, {x: 600, y: 600}, {x: 600, y: 200}], color: "#ef3d61"},
    {p: [{x: 600, y: 200}, {x: 600, y: 600}, {x: 400, y: 400}], color: "#f9f51a"},
    {p: [{x: 400, y: 400}, {x: 600, y: 600}, {x: 400, y: 800}, {x: 200, y: 600}], color: "#a594c0"},
    {p: [{x: 200, y: 600}, {x: 400, y: 800}, {x: 0, y: 800}], color: "#fa8ecc"},
    {p: [{x: 800, y: 400}, {x: 800, y: 800}, {x: 400, y: 800}], color: "#f6ca29"}
];//七巧板的七块图形,p为各顶点坐标,color为颜色
window.onload = function () {
    var canvas = document.getElementById("canvas");
    if (canvas.getContext("2d")) {//判断浏览器是否支持canvas
        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.closePath();
            cxt.fillStyle = piece.color;
            cxt.fill();

            cxt.strokeStyle = "black";
            cxt.lineWidth = 5;
            cxt.stroke();
        }

    } else {
        alert("不支持canvas,请更换浏览器!")
    }

};

最终效果如下所示:

canvas绘制七巧板_第1张图片
七巧板

下一节,我们学习如何使用canvas绘制弧线和圆

你可能感兴趣的:(canvas绘制七巧板)