How set a identification to Canvas Path? - html

Good morning everyone.
I'm building a graph for the enterprise system where I work, but I came across a problem where I need to insert some kind of identification, that I may be rescued by JavaScript (name, id, label, ...).
Someone could tell me how I could do to identify each element of the graph separately? To be more exact, what I'm wondering identifies each element arc is created.
If someone wanted to see the code to understand it better, I'll put the link here:
- JS Bin

Nothing you draw on the canvas is automatically remembered or labeled with an id.
All canvas drawings become forgotten and inaccessible pixels. However there are ways of keeping track of your various drawings.
Instead of keeping your posX,posY and color info in separate parallel arrays, how about creating an object for each node.
Then you could add the id property to each node object:
var nodes=[];
nodes.push({id:"sun", x:100, y:100, color:"yellow"});
nodes.push({id:"earth", x:50, y:50, color:"blue"});
nodes.push({id:"moon", x:50, y:60, color:"gray"});
And, of course, pull the graphing info from each node...
You can draw your graph inside a function and apply a scaleFactor when needed.
function drawGraph(){
context.clearRect(0,0,canvas.width,canvas.height);
context.save();
context.scale(scaleFactor,scaleFactor);
for(var i=0; i<nodes.length;i++){
var node=nodes[i];
context.beginPath();
context.moveTo(centerCanvasX,centerCanvasY);
context.lineTo(node.x,node.y);
context.stroke();
context.beginPath();
context.arc(node.x,node.y,node.radius,0,Math.PI*2,false);
context.closePath();
context.stroke();
context.fillStyle=node.color;
context.fill();
}
context.restore();
}
For dragging/clicking/etc, You could hit test each node array element until you found a match.
function hit(x,y){
for(var i=0;i<nodes.length;i++){
var node=nodes[i];
var dx=node.x-x;
var dy=node.y-y;
var rr=node.radius;
if(dx*dx+dy*dy<rr*rr){
return(i);
}
}
return(-1);
}
The matching element would have the id you need.
If your graph is scaled and you're using mouse coordinates to drag, you must adjust the coordinates that the browser gives you by the current scaleFactor of your graph:
mouseX=parseInt(event.clientX-offsetX)/scaleFactor;
mouseY=parseInt(event.clientY-offsetY)/scaleFactor;
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/c4hsW/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var centerCanvasX=canvas.width/2;
var centerCanvasY=canvas.height/2;
var startX;
var startY;
var isDown=false;
var nodes=[];
var dragNode;
var scaleFactor=1.00;
nodes.push({id:"sun", x:centerCanvasX, y:centerCanvasY, radius:20, color:"yellow"});
nodes.push({id:"earth", x:50, y:50, radius:5, color:"blue"});
nodes.push({id:"moon", x:50, y:65, radius:3, color:"gray"});
drawGraph();
function drawGraph(){
context.clearRect(0,0,canvas.width,canvas.height);
context.save();
context.scale(scaleFactor,scaleFactor);
for(var i=0; i<nodes.length;i++){
var node=nodes[i];
context.beginPath();
context.moveTo(centerCanvasX,centerCanvasY);
context.lineTo(node.x,node.y);
context.stroke();
context.beginPath();
context.arc(node.x,node.y,node.radius,0,Math.PI*2,false);
context.closePath();
context.stroke();
context.fillStyle=node.color;
context.fill();
}
context.restore();
}
function hit(x,y){
for(var i=0;i<nodes.length;i++){
var node=nodes[i];
var dx=node.x-x;
var dy=node.y-y;
var rr=node.radius;
if(dx*dx+dy*dy<rr*rr){
return(i);
}
}
return(-1);
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX)/scaleFactor;
mouseY=parseInt(e.clientY-offsetY)/scaleFactor;
var i=hit(mouseX,mouseY);
if(i>=0){
startX=mouseX;
startY=mouseY;
isDown=true;
dragNode=nodes[i];
}
}
function handleMouseUp(e){
isDown=false;
}
function handleMouseOut(e){
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
// get the current mouse position
mouseX=parseInt(e.clientX-offsetX)/scaleFactor;
mouseY=parseInt(e.clientY-offsetY)/scaleFactor;
// reposition the dragged node
dragNode.x+=(mouseX-startX);
dragNode.y+=(mouseY-startY);
startX=mouseX;
startY=mouseY;
// redraw the graph
drawGraph();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
$("#bigger").click(function(){
scaleFactor+=0.20;
drawGraph();
});
$("#smaller").click(function(){
scaleFactor-=0.20;
drawGraph();
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="bigger">Scale Up</button>
<button id="smaller">Scale Down</button><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Related

Add Href to canvas element

I am using HexagonTools to draw hexagon using canvas.
I need to add an href link to elements of canvas.
I have tried this code:
function drawHexGrid()
{
var linkText="http://stackoverflow.com";
var linkX=5;
var linkY=15;
var linkHeight=10;
var linkWidth;
var inLink = false;
var grid = new HT.Grid(800, 600);
var canvas = document.getElementById("hexCanvas");
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 800, 600);
for(var h in grid.Hexes)
{
grid.Hexes[h].draw(ctx);
linkWidth=ctx.measureText(linkText).width;
canvas.addEventListener("mousemove", on_mousemove, false);
canvas.addEventListener("click", on_click, false);
}
}
But this is not working, I need a simple example on how to develop this, I have already looked at this SOF Question
But I couldn't develop it
You can test which hexagon you mouse clicked using context.isPointInPath.
Listen for mousedown events
In mousedown, fetch the mouseX, mouseY
Recreate each of your hex paths (no need to actually stroke/fill them).
For each hex, use .isPointInPath(mouseX,mouseY) to see if the mouse clicked in this hex.
If you find a clicked hex, use window.open(theUrl, '_blank') to navigate to its associated url.
In Hexagon Tools, each hex has a points property which you can use to receate each of your hex paths.
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
var isDown=false;
var startX,startY;
var hexes=[];
hexes.push({
points:[{x:57.5,y:63},{x:42.5,y:63},{x:35,y:50},{x:42.5,y:37},{x:57.5,y:37},{x:65,y:50}],
url:'http://stackoverflow.com',
});
draw();
$("#canvas").mousedown(function(e){handleMouseDown(e);});
function draw(){
for(var i=0;i<hexes.length;i++){
var h=hexes[i];
ctx.beginPath();
ctx.moveTo(h.points[0].x,h.points[0].y);
for(var j=1;j<h.points.length;j++){
ctx.lineTo(h.points[j].x,h.points[j].y);
}
ctx.closePath();
ctx.stroke();
}
}
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
for(var i=0;i<hexes.length;i++){
var h=hexes[i];
ctx.beginPath();
ctx.moveTo(h.points[0].x,h.points[0].y);
for(var j=1;j<h.points.length;j++){
ctx.lineTo(h.points[j].x,h.points[j].y);
}
ctx.closePath();
//if(ctx.isPointInPath(mouseX,mouseY)){ window.open(h.url, '_blank'); }
if(ctx.isPointInPath(mouseX,mouseY)){ alert('Navigate to: '+h.url); }
}
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click in the hexagon to navigate to Stackoverflow.com</h4>
<canvas id="canvas" width=300 height=300></canvas>

inclined calendar with html5 and css3 and / or any other idea

I need something like the picture shown in the link below, I have no idea how to do it, the most important think is that the calendar is generated dynamically.... this calendar 'll display in a web page.
Interesting project!
You can use canvas transforms to radiate your calendar around a centerpoint.
A Demo: http://jsfiddle.net/m1erickson/Q7S9L/
The idea is to draw a line of your calendar vertically into a column:
And then rotate that column using canvas transforms.
Transforms include context.translate (which moves) and context.rotate (which rotates)
// save the context state
ctx.save();
// translate to the centerpoint around which we will rotate the column
ctx.translate(cx,cy);
// rotate the canvas (which will rotate the column)
ctx.rotate( desiredRadianAngle );
// now draw the column and it will be rotated to the desired angle
Here's example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var year=2014;
var PI2=Math.PI*2;
var cx=375;
var cy=375;
var radialIncrement=15;
var rotationIncrement=-Math.PI/31;
var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var days=[31,28,31,30,31,30,31,31,30,31,30,31];
var dayNames=['Su','M','Tu','W','Th','F','Sa','Su','M','Tu','W','Th','F','Sa','Su','M','Tu','W','Th','F','Sa','Su','M','Tu','W','Th','F','Sa','Su','M','Tu','W','Th','F','Sa','Su','M','Tu','W','Th','F','Sa'];
var monthsFirstWeekday=[]
for(var m=1;m<=12;m++){
monthsFirstWeekday.push(new Date(m+"/01/"+year).getDay());
}
for(var d=0;d<=38;d++){
ctx.save();
ctx.translate(cx,cy);
ctx.rotate(rotationIncrement*(31-d)+Math.PI/2);
var x=-3;
var y=-13*radialIncrement-150;
ctx.font="12px verdana";
ctx.fillStyle="blue";
ctx.fillText(dayNames[d],x,y);
ctx.restore();
}
for(var m=0;m<months.length;m++){
ctx.save();
ctx.translate(cx,cy+25);
ctx.rotate(Math.PI*3/2);
ctx.fillStyle="blue";
ctx.fillText(months[m],0,-(months.length-m)*radialIncrement-150);
ctx.restore();
}
for(var d=0;d<=38;d++){
ctx.save();
ctx.translate(cx,cy);
ctx.rotate(rotationIncrement*(31-d)+Math.PI/2);
for(var m=0;m<months.length;m++){
var x=0;
var y=-(months.length-m)*radialIncrement-150;
var dd=d-monthsFirstWeekday[m]+1;
if(dd>0 && dd<=days[m]){
ctx.fillStyle="black";
ctx.fillText(dd,x,y);
}else{
ctx.beginPath();
ctx.arc(x+3,y,1,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle="red";
ctx.fill();
}
}
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=775 height=650></canvas>
</body>
</html>

Connect canvas with lines

I need to connect two canvas with a line to create a dynamic workflow.
I'll generate the canvas rectangle dynamic (amount of steps I have at DB) but I need to connect the steps with lines.
Anybody have some ideas?
Here’s how to automatically connect 2 draggable canvas rectangles with a line
First, define some boxes and connectors:
// define any boxes that will be drawn
var boxes=[];
boxes.push({x:50,y:25,w:75,h:50}); // x,y,width,height
boxes.push({x:200,y:100,w:50,h:50});
// define any connectors between any boxes
var connectors=[];
connectors.push({box1:0,box2:1});
Draw the boxes and automatically draw their connectors:
function draw(){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<boxes.length;i++){
var box=boxes[i];
ctx.fillRect(box.x,box.y,box.w,box.h);
}
for(var i=0;i<connectors.length;i++){
var connector=connectors[i];
var box1=boxes[connector.box1];
var box2=boxes[connector.box2];
ctx.beginPath();
ctx.moveTo(box1.x+box1.w/2,box1.y+box1.h/2);
ctx.lineTo(box2.x+box2.w/2,box2.y+box2.h/2);
ctx.stroke();
}
}
The code below allows any box to be dragged and remain connected.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/GX6HS/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:20px;}
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var startX;
var startY;
var isDown=false;
var dragTarget;
var boxes=[];
boxes.push({x:50,y:25,w:75,h:50}); // x,y,width,height
boxes.push({x:200,y:100,w:50,h:50});
var connectors=[];
connectors.push({box1:0,box2:1});
draw();
function draw(){
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
for(var i=0;i<boxes.length;i++){
var box=boxes[i];
ctx.fillRect(box.x,box.y,box.w,box.h);
}
for(var i=0;i<connectors.length;i++){
var connector=connectors[i];
var box1=boxes[connector.box1];
var box2=boxes[connector.box2];
ctx.beginPath();
ctx.moveTo(box1.x+box1.w/2,box1.y+box1.h/2);
ctx.lineTo(box2.x+box2.w/2,box2.y+box2.h/2);
ctx.stroke();
}
}
function hit(x,y){
for(var i=0;i<boxes.length;i++){
var box=boxes[i];
if(x>=box.x && x<=box.x+box.w && y>=box.y && y<=box.y+box.h){
dragTarget=box;
return(true);
}
}
return(false);
}
function handleMouseDown(e){
startX=parseInt(e.clientX-offsetX);
startY=parseInt(e.clientY-offsetY);
// Put your mousedown stuff here
isDown=hit(startX,startY);
}
function handleMouseUp(e){
// Put your mouseup stuff here
dragTarget=null;
isDown=false;
}
function handleMouseOut(e){
handleMouseUp(e);
}
function handleMouseMove(e){
if(!isDown){return;}
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// Put your mousemove stuff here
var dx=mouseX-startX;
var dy=mouseY-startY;
startX=mouseX;
startY=mouseY;
dragTarget.x+=dx;
dragTarget.y+=dy;
draw();
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Drag boxes--they remain connected</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

is mouse in user drawn area on canvas

Basically, a user uploads a picture and then can paint on it, and save the result. Another user can then view the photo and if they click in the same area as painted, something happens.
So user 1 can make an area click-able for user 2 by drawing on the photo.
now the upload bit is fine, and painting with help from a tutorial and example I've got sussed out. But defining what area is click-able is a bit harder. For something like a rectangle its easy enough, I made an example.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var button = new Object();
button.x = 50;
button.y = 50;
button.width = 50;
button.height = 50;
button.rgb = "rgb(0, 0, 255)";
function drawbutton(buttonobject)
{
context.fillStyle = buttonobject.rgb;
context.fillRect (buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
context.strokeRect(buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
}
drawbutton(button);
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY)
{
if(((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height))))
return true;
else
return false;
}
$("#myCanvas").click(function(eventObject) {
mouseX = eventObject.pageX - this.offsetLeft;
mouseY = eventObject.pageY - this.offsetTop;
if(checkIfInsideButtonCoordinates(button, mouseX, mouseY))
{
button.rgb = "rgb(0, 255, 0)";
drawbutton(button);
} else {
button.rgb = "rgb(255, 0, 0)";
drawbutton(button);
}
});
but when it comes to other shapes like circles, or just someone smothering the page, how would you go about detecting that ?
one thought I had was using the edited layer, making it hidden, and detecting a pixel color of say blue, from here but that limits the color use of the photo and im not entirely sure how to implement it. any other ideas ?
EDIT:
I figured out circles after some tinkering, using Pythagoras theorem to see if mouse coordinates are smaller than the radius, but this assumes circle center of 0,0, so then offset mouse by circles actual center. example
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY) {
actualX = mouseX - buttonObj.x
actualY = mouseY - buttonObj.y
mousesqX = actualX * actualX
mousesqY = actualY * actualY
sqR = buttonObj.r * buttonObj.r
sqC = mousesqX + mousesqY
if (sqC < sqR) return true;
else return false;
}
Here’s how to test whether user#2 is inside user#1’s paintings
Create a second canvas used to hit-test whether user#2 is inside of user#1’s paintings.
The hit-test canvas is the same size as the drawing canvas, but it only contains user#1’s paintings…not the image.
When user#1 is painting, also draw their paintings on the hit canvas.
When user#1 is done painting, save all their paintings from the hit canvas.
You have at least 2 ways to save user#1’s paintings from the hit canvas:
Serialize all the canvas commands needed to recreate the shapes/paths that user#1 paints.
Save the hit canvas as an image using canvas.toDataURL.
When user#2 clicks, check if the corresponding pixel on the hit canvas is filled or is transparent (alpha>0).
// getImageData for the hit-test canvas (this canvas just contains user#1's paintings)
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
// look at the pixel under user#2's mouse
// return true if that pixel is filled (not transparent)
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/etA5a/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:15px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var hit=document.getElementById("hit");
var hitCtx=hit.getContext("2d");
var user2=document.getElementById("user2");
var ctx2=user2.getContext("2d");
var canvasOffset=$("#user2").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var imageDataData;
var hitWidth=hit.width;
var img=document.createElement("img");
img.onload=function(){
// left canvas: image+user#1 paintings
ctx.globalAlpha=.25;
ctx.drawImage(img,0,0);
ctx.globalAlpha=1.00;
scribble(ctx,"black");
// mid canvas: just user#1 paintings (used for hittests)
scribble(hitCtx,"black");
// right canvas: user#2
ctx2.drawImage(img,0,0);
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
function scribble(context,color){
context.beginPath();
context.moveTo(70,2);
context.lineTo(139,41);
context.lineTo(70,41);
context.closePath();
context.rect(39,54,22,30);
context.arc(73,115,3,0,Math.PI*2,false);
context.fillStyle=color;
context.fill();
}
function handleMouseMove(e){
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// If user#2 has a hit on user#1's painting, mid-canvas turns red
var color="black";
if(isHit(mouseX,mouseY)){ color="red"; }
scribble(hitCtx,color);
}
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
$("#user2").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Left: original image with user#1 painting</p>
<p>Mid: user#1 painting only (used for hit-testing)</p>
<p>Right: user#2 (move mouse over hit areas)</p>
<canvas id="canvas" width=140 height=140></canvas>
<canvas id="hit" width=140 height=140></canvas>
<canvas id="user2" width=140 height=140></canvas><br>
</body>
</html>

Canvas: Click event on line

Please take a look at this little example. The clickhandler only works if you click in the middle of the line. It seems that the method isPointInPath does not consider the width of the line. Is there a way to solve this problem?
Yes, you are correct.
The new isPointInPath() works only on the centerline of a "fat" line--not the full width of the line.
It's more user friendly on closed shapes that are more than 1 pixel wide ;)
A Workaround for your exact question: Instead of drawing a fat line, draw a 20px wide rectangle.
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/QyWDY/
This code uses basic trigonometry to create a rectangle around a line. In the mousedown event handler, it redraws the rectangle transparently and then tests isPointInPath().
If you need to test a poly-line, you can use these same principles to make rectangle-lines for each segment of your poly-line.
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// get canvas's relative position
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
// line specifications
var x1=50;
var y1=50;
var x2=300;
var y2=100;
// draw the lineRectangle
var lineRect=defineLineAsRect(x1,y1,x2,y2,20);
drawLineAsRect(lineRect,"black");
// overlay the line (just as visual proof)
drawLine(x1,y1,x2,y2,3,"red");
function drawLine(x1,y1,x2,y2,lineWidth,color){
ctx.fillStyle=color;
ctx.strokeStyle=color;
ctx.lineWidth=lineWidth;
ctx.save();
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
ctx.restore();
}
function drawLineAsRect(lineAsRect,color){
var r=lineAsRect;
ctx.save();
ctx.beginPath();
ctx.translate(r.translateX,r.translateY);
ctx.rotate(r.rotation);
ctx.rect(r.rectX,r.rectY,r.rectWidth,r.rectHeight);
ctx.translate(-r.translateX,-r.translateY);
ctx.rotate(-r.rotation);
ctx.fillStyle=color;
ctx.strokeStyle=color;
ctx.fill();
ctx.stroke();
ctx.restore();
}
function defineLineAsRect(x1,y1,x2,y2,lineWidth){
var dx=x2-x1; // deltaX used in length and angle calculations
var dy=y2-y1; // deltaY used in length and angle calculations
var lineLength= Math.sqrt(dx*dx+dy*dy);
var lineRadianAngle=Math.atan2(dy,dx);
return({
translateX:x1,
translateY:y1,
rotation:lineRadianAngle,
rectX:0,
rectY:-lineWidth/2,
rectWidth:lineLength,
rectHeight:lineWidth
});
}
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
// draw our lineRect
drawLineAsRect(lineRect,"transparent");
// test if hit in the lineRect
if(ctx.isPointInPath(mouseX,mouseY)){
alert('Yes');
}
}
canvas.addEventListener("mousedown", handleMouseDown, false);
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=310 height=115></canvas>
</body>
</html>