0 Replies - 702 Views - Last Post: 26 April 2012 - 10:33 AM

#1 LaNiZ   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 24-September 09

Detect if any drawing in a canvas is within 25 px of the mouse

Posted 26 April 2012 - 10:33 AM

Hello,

This is more of a Mathematical problem than a Javascript problem but since i want to implement this in JS/Jquery i'll post here.

So, i want to be able to detect lines and/or drawings on a canvas within a set radius of the mouse position.

I have a canvas, named "PC" and it's context in "map". I also have a few drawings stored in an array named "Objects".

My Drawings which are stored in the "Objects" array is really just functions / objects:

function Line(x1, y1, x2, y2) {
	this.x1 = x1;
	this.y1 = y1;
	this.x2 = x2;
	this.y2 = y2;
	this.color = "gray";
	
	this.Paint = function() {
		map.beginPath();
		map.strokeStyle = this.color;
		map.lineCap = "butt";
		map.lineWidth = 3;
		map.moveTo(this.x1, this.y1);
		map.lineTo(this.x2, this.y2);
		map.stroke();
		map.closePath();
	};
}



Now this is the code i have:

var map = $("#map")[0].getContext("2d");
var Objects = [new Line(50,50,100,50), new Line(100,50,100,100), new Line(100,100,50,100), new Line(50,100,50,50)];

function PaintAll(){
	map.clearRect(0, 0, 500, 500) //My canvas is 500x500px
	var i = 0;
	for(i in Objects){
		if(Objects[i] !== null) Objects[i].Paint();
	}
}

$("#map").bind("mousemove", function(e){
	/* Detect if any of the Lines in "Objects" is within the radius */
    var i = 0;
    for(i in Objects){
        //... Help?
        
        /*Here's Psudo Code:
        if(Objects[i].within(e.pageX, e.pageY, 25)){
            Objects[i].color = "red";
        }else{
            Objects[i].color = "gray";
        }
        */
    }
    
    PaintAll();
    
    /* Paint Mouse Radius */
    map.beginPath();
    map.arc(e.pageX, e.pageY, 25, 0, Math.PI * 2, true);
    map.stroke();
    map.closePath();
});

/* First Draw */
PaintAll();



Is This A Good Question/Topic? 0
  • +

Page 1 of 1