Draw 4 straight lines on image with overlay - Javascript Canvas

Javascript examples for Canvas:image

Description

Draw 4 straight lines on image with overlay

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>

canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){//from  w  ww  . ja  v  a2  s. com
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var image=new Image();
    image.onload=function(){
        slice(image);
    }
    image.src="https://www.java2s.com/style/demo/InternetExplorer.png";
    function slice(img){
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var w=img.width;  // original image width
        var h=img.height; // original image height
        var rows=3;       // # of rows
        var cols=3;       // # of columns
        var cw=w/rows;    // cell width
        var ch=h/cols;    // cell height
        var scale=3;      // also, scale the image down
        var spacing=5;    // spacing between cells

        canvas.width=w/scale+spacing*2;
        canvas.height=h/scale+spacing*2;
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(var y=0;y<3;y++){
            for (var x=0;x<3;x++){
                ctx.drawImage(img,x*cw,y*ch,cw,ch,
                    x*(cw/scale+spacing),y*(ch/scale+spacing),cw/scale,ch/scale)
            }
        }
        ctx.stroke()
    }
}); // end $(function(){});

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

Related Tutorials