1
votes

I have this code that let me draw rectangle on canvas: https://jsfiddle.net/6u7bLkwc/4/

In order to draw a rectangle on the canvas, click on the image and then drag your mouse.

To reproduce my problem please follow this steps:

  • Draw a rectangle like mentionned in the top.
  • And then click on ADD TEXT button.
  • Now try to draw another rectangle, you will see that your cursor are not in the same way with the rectangle.

How to make my code work even if i add or remove any elements on the page dynamically?

I tried to do like this:

var shape = new Shape(mouseDownX - canvasOffset.left, mouseDownY - canvasOffset.top, mouseX - mouseDownX, mouseY - mouseDownY, color);

But didn't resolved it.

Something like updating new positions will solve it, but not have idea about how to process.

1
Check the solution below :)Yehia Awad
This not solved the problem totally, please look here about the same script but still the problem there: jsfiddle.net/dkboaq7p/1Jis Maxi
check again the first and second example you have provided are different casesYehia Awad
@YehiaAwad check the last case, is what i am looking for to solve.Jis Maxi

1 Answers

1
votes

check the solution over here : https://jsfiddle.net/6u7bLkwc/9/

the problem is that you are not calculating the PageX and PageY relative to the canvas position, but instead to the whole page which is giving you wrong coordinates.

I have just changed these:

mouseDownX = e.pageX;
mouseDownY = e.pageY;

to this:

mouseDownX = e.pageX - this.offsetLeft;
mouseDownY = e.pageY - this.offsetTop;

UPDATE

For some other cases you should just use getBoundingClientRect() method on the canvas to get the element position relative to the viewport as the following jsfiddle shows sfiddle.net/dkboaq7p/2

// Get Element's relative position

var canvasPosition=document.getElementById("canvas").getBoundingClientRect();

  mouseDownX =  e.pageX - canvasPosition.left;
  mouseDownY =  e.pageY - canvasPosition.top;