Add different parallel lines on a canvas - Javascript Canvas

Javascript examples for Canvas:Line

Description

Add different parallel lines on a canvas

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(){/*  ww w  . j  a  va2  s.c  o m*/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var isDown=false;
    var startY;
    var layers=[];
    var currentColor="black";
    function handleMouseDown(e){
      e.preventDefault();
      startX=parseInt(e.clientX-offsetX);
      startY=parseInt(e.clientY-offsetY);
      currentColor=randomColor();
      isDown=true;
    }
    function handleMouseUp(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      isDown=false;
      layers.push({y1:startY,y2:mouseY,color:currentColor});
    }
    function handleMouseOut(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      isDown=false;
      layers.push({y1:startY,y2:mouseY,color:currentColor});
    }
    function handleMouseMove(e){
      if(!isDown){return;}
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      drawAll();
      hLine(startY,currentColor);
      hLine(mouseY,currentColor);
    }
    function drawAll(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        for(var i=0;i<layers.length;i++){
            layer=layers[i];
            hLine(layer.y1,layer.color);
            hLine(layer.y2,layer.color);
        }
    }
    function hLine(y,color){
        ctx.beginPath();
        ctx.moveTo(0,y);
        ctx.lineTo(canvas.width,y);
        ctx.strokeStyle=color;
        ctx.stroke();
    }
    function randomColor(){
        return('#'+Math.floor(Math.random()*16777215).toString(16));
    }
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});

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

Related Tutorials