admin管理员组

文章数量:1319004

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 ?

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 ?

Share Improve this question asked Mar 26, 2014 at 8:15 VostanAzatyanVostanAzatyan 6472 gold badges9 silver badges23 bronze badges 4
  • 2 When drawing, just keep the second end's X or Y (depending on the orientation) the same as the starting point's one as opposed to the mouse's one. – PurkkaKoodari Commented Mar 26, 2014 at 8:17
  • These kind of things would need some trigonometry to make the calculations. – user3111737 Commented Mar 26, 2014 at 8:22
  • what you have tried so far? – db9dreamer Commented Mar 26, 2014 at 8:36
  • 1 U just need to use some logic, no plugins will help,Check my solution below – Amarnath R Shenoy Commented Mar 26, 2014 at 9:24
Add a ment  | 

1 Answer 1

Reset to default 5

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/zhq5n/4/

Better one here by GameAlchemist

http://jsfiddle/gamealchemist/zhq5n/5/

本文标签: javascripthow draw only vertical and horizontal lines (Canvas)Stack Overflow