I have this discussion which indicates how to make a pencil tool.
How can I detect whether the mouse is hovering on drawn area/points/images using the pencil tool? T
Here's a quick demo. Move your mouse within 5px of either end of the line to see the guides.
The idea is that it uses collision detection to work out if the mouse is within 5 pixels of the start or end of the line.
You can easily change from ugly square guides to a circle. You can essentially do what you want.
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 400;
document.body.appendChild(canvas);
//add as many lines as you want
var lines = [
{start: {x: 100, y: 100}, end: {x: 200, y: 300}},
{start: {x: 200, y: 150}, end: {x: 50, y: 250}},
{start: {x: 240, y: 240}, end: {x: 450, y: 150}},
{start: {x: 160, y: 340}, end: {x: 10, y: 90}},
{start: {x: 380, y: 270}, end: {x: 300, y: 380}}
];
function render(){
ctx.clearRect(0,0,500,400);
for(var c = 0; c < lines.length; c++){
ctx.moveTo(lines[c].start.x, lines[c].start.y);
ctx.lineTo(lines[c].end.x, lines[c].end.y);
ctx.stroke();
}
}
render();
var mouse = {x: 0, y: 0};
document.addEventListener('mousemove', function(e){
mouse.x = e.clientX;
mouse.y = e.clientY;
render();
for(var c = 0; c < lines.length; c++){
if(
//check if within 10px of start of line
(mouse.x > lines[c].start.x - 5 &&
mouse.x < lines[c].start.x + 5 &&
mouse.y > lines[c].start.y - 5 &&
mouse.y < lines[c].start.y + 5) ||
//same for the end of the line
(mouse.x > lines[c].end.x - 5 &&
mouse.x < lines[c].end.x + 5 &&
mouse.y > lines[c].end.y - 5 &&
mouse.y < lines[c].end.y + 5)
){
showGuides(c);
}
}
});
//function to show the guides
function showGuides(i){
ctx.fillRect(lines[i].start.x - 5, lines[i].start.y - 5, 10, 10);
ctx.fillRect(lines[i].end.x - 5, lines[i].end.y - 5, 10, 10);
}
body{
margin: 0;
}
^ ^ ^
| | |
Run code snippet