Canvas 矩形绘制

 

效果图:

 

 知识点:

1、context.beginPath();

2、context.closePath();

3、context.Rect(x,y,width,heght);

     context.fllRect(x,y,width,heght);

     context.strokeRect(x,y,width,heght);

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            *{
                padding: 0;
                margin: 0;
            }
            
            #canvas{
                border:1px solid #ccc;
            }
        </style>
    </head>
    <body>
        <canvas id="canvas">您的浏览器不支持</canvas>
    </body>
    <script>
        var canvas=document.getElementById("canvas");
        canvas.width=500;
        canvas.height=500;
        var ctx=canvas.getContext("2d");
        drawRect(ctx,100,100,200,200,2,"#530882","yellow");
        drawRect2(ctx,200,200,200,200,2,"#530882","rgba(0,250,0,0.5)");//可以通过rgba 控制颜色的透明度
    
        
        //绘制矩形函数
        function drawRect(ctx,x,y,width,height,borderwidth,bordercolor,fillcolor){
            ctx.beginPath();//开始一个新的绘画
    
            ctx.moveTo(x,y);//画笔移动到起点
            ctx.lineTo(x+width,y);
            ctx.lineTo(x+width,y+height);
            ctx.lineTo(x,y+height);
            ctx.closePath();//封闭图形,在起点和终点间连线。
            
            ctx.lineWidth=borderwidth;
            ctx.fillStyle=fillcolor;
            ctx.strokeStyle=bordercolor;
            
            ctx.fill();//填充
            ctx.stroke();//绘制
        }
        
        //绘制矩形函数2
        function drawRect2(ctx,x,y,width,height,borderwidth,bordercolor,fillcolor){
            ctx.lineWidth=borderwidth;
            ctx.fillStyle=fillcolor;
            ctx.strokeStyle=bordercolor;
            
            ctx.fillRect(x,y,width,height);//绘制填充矩形
            ctx.strokeRect(x,y,width,height);//绘制矩形
        }
        
    </script>
</html>

 

posted @ 2019-11-21 21:05  梁涛999  阅读(151)  评论(0编辑  收藏  举报