2

I want to Draw a line and make it drag-able from both the Ends. Using the mouse click i am able to draw the line but i want to drag the line and resize it later.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.moveTo(10,20);
ctx.lineTo(100, 120);
ctx.stroke();

Suppose if i am dragging point b to (200,150)
then the coordinates should be point A(10,20) and point B(200,150).

Charlie
  • 530
  • 10
  • 26
ram
  • 21
  • 5
  • 1
    Possible duplicate of [How to Create a Draggable Line in HTML5 Canvas?](https://stackoverflow.com/questions/5559248/how-to-create-a-draggable-line-in-html5-canvas) – SanSolo Jan 14 '19 at 06:39
  • In that he is dragging the nearest line but i want to drag both the edge of the line. – ram Jan 14 '19 at 07:11
  • Suppose if i am dragging point b then the coordinates should be. – ram Jan 14 '19 at 10:33
  • Hi @ram welcome to SO. Using canvas you are basically going to have to do everything the hard way (unless you use a library which provides the functionality you want). The canvas doesn't have any concept of the line that is drawn on it or which end is which. It just knows that there are a bunch of coloured pixels. You know they look like a line. The canvas doesn't care. If you need to respond when your mouse is over the end of the line then you will have to detect the cursor position, compare it to where you know then end of the line is etc etc etc. – El Ronnoco Jan 14 '19 at 11:19
  • For example see this gentleman's noble efforts to do something similar... https://simonsarris.com/making-html5-canvas-useful/ – El Ronnoco Jan 14 '19 at 11:22
  • if not canvas then using any other thing is it possible. I want to draw some shape using lines and after drawing i should be able to drag and adjust the drawn shape. – ram Jan 14 '19 at 12:03

1 Answers1

2

Answer:

You can't easily access the line you draw in a canvas, and you have to draw the entire canvas new if you want to alter it (that is how a canvas works). If you want to add an event handler to a drawn property, you should use svg for drawing such content:

Differences Between SVG and Canvas:

  • SVG is a language for describing 2D graphics in XML.
  • Canvas draws 2D graphics, on the fly (with a JavaScript).
  • SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.
  • In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are changed, the browser can automatically re-render the shape.
  • Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the browser. If its position should be changed, the entire scene needs to be redrawn, including any objects that might have been covered by the graphic.

Tutorial:

Stephan T.
  • 5,843
  • 3
  • 20
  • 42