绘制矩形

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
            #canvas1{
                margin: 0 auto;
                /*background: #efefef;*/
                display: block;
                border: 1px solid #aaa;
                /* 600px;
                height: 400px;*/
            }
        </style>
    </head>
    <body>
        <canvas id="canvas1" width="600" height="400">
            你的浏览器不支持canvas
        </canvas>
        
        
        <script type="text/javascript">
        //找到要设置的画布
            var canvas1 = document.querySelector('#canvas1')
        //能够对这个画布画画的对象,就是画笔,canvas1的上下文对象
            var ctx = canvas1.getContext('2d')
            console.log([canvas1])
            console.log(ctx)
            //设置内容填充的颜色
            ctx.fillStyle = 'skyblue'
            
            //绘制矩形的方式1
            ctx.fillRect(20,20,100,50)
            
            //绘制矩形的方式2
            ctx.beginPath()
            ctx.rect(20,100,100,50)
            ctx.fill()
            ctx.closePath()
            
            //绘制矩形的路径
            ctx.beginPath()
            ctx.strokeStyle = 'deeppink'
            ctx.rect(20,180,100,50)
            ctx.stroke()
            ctx.closePath()
            
            
            
            
        </script>
        
    </body>
</html>
原文地址:https://www.cnblogs.com/wwthuanyu/p/10555381.html