canvas:利用js遍历绘制七巧板

<pre name="code" class="javascript"><pre name="code" class="html"><!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style></style>
</head>
<body>
<canvas id="canvas" width="600" height="600" style="display: block; margin:50px auto;border: 1px solid #ddd;">
    该浏览器不支持canvas标签;
</canvas>
</body>
<script>
    /*canvas基于状态进行绘制图形*/
    /* if(canvas.getContext("2d")){
     }else{
     alert("该浏览器不支持canvas标签")
     }*/
   var tangram = [  //创建一个数组,里面放置7个要绘制的对象,对象的属性包括:绘制点 颜色;
        {p: [{x: 0, y: 0}, {x: 600, y: 0}, {x: 300, y: 300}], color: "#caff67"},
        {p: [{x: 0, y: 0}, {x: 300, y: 300}, {x: 0, y: 600}], color: "#67becf"},
        {p: [{x: 600, y: 0}, {x: 600, y: 300}, {x: 450, y: 450}, {x: 450, y: 150}], color: "#ef3d61"},
        {p: [{x: 450, y: 150}, {x: 450, y: 450}, {x: 300, y: 300}], color: "green"},
        {p: [{x: 300, y: 300}, {x: 450, y: 450}, {x: 300, y: 600}, {x: 150, y: 450}], color: "#a594c0"},
        {p: [{x: 150, y: 450}, {x: 300, y: 600}, {x: 0, y: 600}], color: "#fe8ecc"},
        {p: [{x: 600, y: 300}, {x: 600, y: 600}, {x: 300, y: 600}], color: "#f6ca29"}
    ];
    window.onload = function () {   //
        var canvas = document.getElementById("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();
        }

/*window.onload = function () {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    context.beginPath();
    context.moveTo(0,0);
    context.lineTo(300,300);
    context.lineTo(600,0);
    context.fillStyle = "blue";//"rgb("0,10,100");
    context.lineWidth = 5;
    context.strokeStyle ="#e4393c";
    context.fill();
    context.stroke();
    context.closePath();
}*/
</script>
</html>


 

                
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值