Draw a rectangle with fill color and individual borders - Javascript Canvas

Javascript examples for Canvas:Rectangle

Description

Draw a rectangle with fill color and individual borders

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

body{ background-color: ivory; }
#canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){//from   www  .  jav a2  s . c om
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    CanvasRenderingContext2D.prototype.rainbowRect = function (x,y,w,h,fillColor,tColor,rColor,bColor,lColor){
        fillColor=fillColor||this.fillStyle;
        var ss=this.strokeStyle;
        tColor=tColor||ss;
        rColor=rColor||ss;
        bColor=bColor||ss;
        lColor=lColor||ss;

        this.save();
        this.lineJoin="miter";
        function trapezoid(context,color,x1,y1,x2,y2,x3,y3,x4,y4){
            context.beginPath();
            context.moveTo(x1,y1);
            context.lineTo(x2,y2);
            context.lineTo(x3,y3);
            context.lineTo(x4,y4);
            context.closePath();
            context.fillStyle=color;
            context.fill();
        }
        var lw=this.lineWidth/2;

        var L=x-lw;
        var R=x+lw;
        var T=y-lw;
        var B=y+lw;
        // top
        trapezoid(this,tColor,  L,T,  R+w,T,  L+w,B,  R,B );
        // right
        trapezoid(this,rColor,  R+w,T,  R+w,B+h,  L+w,T+h,  L+w,B );
        // bottom
        trapezoid(this,bColor,  R+w,B+h,  L,B+h,  R,T+h,  L+w,T+h );
        // left
        trapezoid(this,lColor,  L,B+h,  L,T,  R,B,  R,T+h );
        // fill
        this.fillStyle=fillColor;
        this.fillRect(x,y,w,h);
        // be kind -- always rewind (old vhs reference!)
        this.restore();
        // don't let this path leak
        this.beginPath();
        // chain
        return(this);
    };
    ctx.lineWidth=20;
    ctx.rainbowRect(100,100,100,50,"gold","red","blue","green","purple");
});

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials