0

I am trying to create a canvas that allows me to draw on it rectangles using mouse events. Very similar to the way selection works in windows, I want to be able to click down anywhere on my page, drag left/right/up/down, then once I release, a rectangle is drawn with the starting coordinates (x1 and y1) on mousedown and the ending coordinates (x2, y2) on mouseup.

I've been trying to create eventListeners bound to my canvas that return the starting and ending coordinates on mousedown and mouseup respectively, but my variables stay undefined.

My canvas spans the entire length of my window so no need to take into account relative positioning. Also the solution has to be implemented using purely Javascript, no JQuery allowed.

Thank you for your help!

1 Answer 1

2

UPDATE

Ignore most of what is underneath, re-reading your question, it seems like you have the theory nailed. Your problem is most likely the mousedown and mouseup function parameters are missing. Try the following;

document.getElementsByTagName('canvas')[0].addEventListener('mousedown', function(e){
 // I THINK IT'S THE e ON THE LINE ABOVE THIS THAT YOU'RE MISSING.
 // YOU CAN THEN ACCESS THE POSITION OF THE MOUSE USING;

 mouse.x = e.pageX;
 mouse.Y = e.pageY;
})

I won't write the code for you, but I can give you theory.

Store your mouse x & y variables in an object such as mouse = {}.

Add an event listener to the canvas for mouse down (click) and store the e.pageX and e.pageY in mouse.firstX and mouse.firstY. Use something like:

document.getElementsByTagName('canvas')[0].addEventListener('mousedown', function(e){ mouse.firstX = e.pageX; mouse.firstY = e.pageY; })

Create a second event listener for the canvas for mouseup and store this set of e.pageX and e.pageY in mouse.secondX and mouse.secondY.

Calculate the difference between firstX and secondX, firstY and secondY to work out big your rectangle sound be.

var width = mouse.firstX + mouse.secondX // rect width

var height = mouse.firstY + mouse.secondY // rect height

Then, using these calculations, draw a rectangle on your canvas using firstX and firstY as the position parameters.

I hope this is relatively clear and helpful for you. If not, this might help;

http://simonsarris.com/blog/140-canvas-moving-selectable-shapes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.