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 ?
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With