how draw only vertical and horizontal lines (Canvas)

canvas, css, html, javascript

Solution

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/

Problem

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... can any one give me some code example ?

Original source