首页 > 代码库 > canvas绘图详解-04-矩形

canvas绘图详解-04-矩形

rect( x , y , width , height );//描述矩形路径
fillRect( x , y , width , heigth );//填充一个矩形
strokeRect( x , y , width , heigth );//描边一个矩形

以上是快捷绘制矩形的函数,你可能要问有fillRect和strokeRect还要rect那个干吗?

下面是三种不同的方式绘制矩形

<script type="text/javascript">
    window.onload=function(){
        var canvas = document.getElementById(‘canvas‘);
        canvas.width = 800;
        canvas.height = 800;
        var context = canvas.getContext(‘2d‘);

        drawRect(context , 100 , 100 , 100 , 100 , 10 , ‘#058‘ , "red");
        drawRect2(context , 150, 100 , 100 , 100 , 10 , ‘#058‘ , "rgba(0,255,0 ,0.5)");
        drawRect3(context , 500 , 100 , 100 , 100 , 10 , ‘#058‘ , "blue");
    }

    function drawRect(cxt , x , y , width , height , borderWidth , borderColor , fillColor) {
        cxt.beginPath();
        cxt.moveTo( x , y);
        cxt.lineTo( x + width , y );
        cxt.lineTo( x + width , y + height);
        cxt.lineTo( x , y + height);
        cxt.closePath();

        cxt.fillStyle = fillColor;
        cxt.lineWidth = borderWidth;
        cxt.strokeStyle = borderColor;

        cxt.fill();
        cxt.stroke();
    }
    function drawRect2(cxt , x , y , width , height , borderWidth , borderColor , fillColor) {
        cxt.beginPath();
        cxt.rect( x , y , width , height);
        cxt.closePath();

        cxt.fillStyle = fillColor;
        cxt.lineWidth = borderWidth;
        cxt.strokeStyle = borderColor;

        cxt.fill();
        cxt.stroke();
    }
    function drawRect3(cxt , x , y , width , height , borderWidth , borderColor , fillColor) {
        cxt.fillStyle = fillColor;
        cxt.lineWidth = borderWidth;
        cxt.strokeStyle = borderColor;

        cxt.fillRect( x , y , width , height);
        cxt.strokeRect(x , y , width , height);
    }
</script>

 

canvas绘图详解-04-矩形