Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how draw only vertical and horizontal lines (Canvas)

I want to make one drawing tool with html5 canvas, that can draw only horizontal and vertical lines

For example despite which way I will drag the mouse it must draw vertical or horizontal line.
Below I will show one image where i will show what i need...

enter image description here

can any one give me some code example ?

like image 582
VostanAzatyan Avatar asked Mar 26 '14 08:03

VostanAzatyan


People also ask

How do I draw a vertical line in canvas?

To draw a line on a canvas, you use the following steps: First, create a new line by calling the beginPath() method. Second, move the drawing cursor to the point (x,y) without drawing a line by calling the moveTo(x, y) . Finally, draw a line from the previous point to the point (x,y) by calling the lineTo(x,y) method.

Which two methods are used to draw straight lines on a canvas?

There are the following methods to draw a straight line on the canvas. beginPath(): This method is used to begin the path that we are going to draw. It does not take any arguments. moveTo(): This method takes two arguments which will be the starting point of any path.


1 Answers

This is something that you have to use some logic or algorithm for.What I have done here is to Calculate dx and dy, ie change in x and change in y.

When change in x is more (dx>dy) keep your y constant, and vice versa.

Here's my code

HTML

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">

Jquery

var prvX = -300;
var prvy = -300;
$('#myCanvas').bind("mousemove",function(e){

    var c=document.getElementById("myCanvas");
    c.width=c.width;  
    var ctx=c.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(20,20);
    var dx = Number(e.offsetX) - Number(prvX);
    var dy = Number(e.offsetY) - Number(prvy);
    if(Number(dx)>Number(dy))
    {
      ctx.lineTo(e.offsetX,20);            
    }
     else
     {
      ctx.lineTo(20,e.offsetY); 
     }
     prvX =e.offsetX;
     prvy=e.offsetY;    
     ctx.stroke();});

Fiddle

http://jsfiddle.net/zhq5n/4/

Better one here by GameAlchemist

http://jsfiddle.net/gamealchemist/zhq5n/5/

like image 136
Amarnath R Shenoy Avatar answered Sep 30 '22 20:09

Amarnath R Shenoy