Help with Javascript canvas

Help with Javascript canvas
0.0 0

#1

Hello guys, I just coded a simple application where users can drag and move two circles inside the Canvas. I used Javascript to implement this. So I I’m just wondering whether someone can help me how to drag the circles without going past the edge of the canvas. The link of the code is provided below. THank you :slight_smile:

https://jsfiddle.net/rafael_dizon/4apa5sxm/3/


#2

Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://freecodecamp.org.

Can you explain which code you have tried (in your current solution) which attempts to stop the circles from going outside the box? We can guide you if you provide us your attempts, but we are not here to just give you a working solution.


#3

I tried inserting this code within the handleMouseMove function to check if the circles stop before it reaches the edge. if(mouseX > 556) { .
clearDragging();
}
But I couldn’t drag it back when it reaches the right edge.


#4

You could modify your drag values if the circle position is outside the limits of canvas.

Extra Hint

Let’s say if the x position of the circle you’re about to draw is higher than width of canvas, set it to width of canvas, if lower than 0, set it to 0.
If you want the whole circle inside the canvas, you might have to use its radius value.

Partial solution

https://jsfiddle.net/4apa5sxm/55/


#5

Thank you so much. I was also able to do it with the Y-axis.