HTML5 Canvas ( 矩形的繪製 ) rect, strokeRect, fillRect

weixin_34391854發表於2017-03-25
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>canvas</title>
    <script type="text/javascript" src="../js/jQuery.js"></script>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
            outline: none;
            border: none;
        }
        #canvas{
            margin: auto auto;
            width: 7rem;
            margin: .25rem 0 0 1.5rem;
            border: 1px solid black;
        }
    </style>
</head>
<body> 
    <canvas id="canvas" width="1000" height="600"></canvas>
</body>
</html>
<script type="text/javascript">
    /**
     * rem 佈局初始化
     */
    $('html').css('font-size', $(window).width()/10);
    /**
     * 獲取 canvas 畫布
     * 獲取 canvas 繪圖上下文環境
     */
    var canvas = $('#canvas')[0];
    var cxt = canvas.getContext('2d');
    
    /**
     * canvas 繪製矩形的方法 一
     * rect(矩形的左上定點橫座標, 矩形的左上定點縱座標, 矩形的寬度, 矩形的高度)
     * 該方法只是描述了 矩形的路徑, 需要呼叫畫線或者填充的方法才能起作用
     */
    cxt.fillStyle = 'yellow';
    cxt.rect(200, 100, 400, 300);
    //cxt.stroke();
    cxt.fill();
    
    /**
     * 繪製矩形的方法二
     * fillRect(矩形的左上定點橫座標, 矩形的左上定點縱座標, 矩形的寬度, 矩形的高度)
     * strokeRect(矩形的左上定點橫座標, 矩形的左上定點縱座標, 矩形的寬度, 矩形的高度)
     * 這兩個方法會直接繪製出圖形
     */
    cxt.fillStyle = 'red';
    //cxt.strokeRect(400, 200, 400, 300);
    cxt.fillRect(400, 200, 400, 300);
</script>

 

相關文章