// gets the center of a table cell relative to the document
function getCellCenter(table, row, column) {
var tableRow = $(table).find('tr')[row];
var tableCell = $(tableRow).find('td')[column];
var offset = $(tableCell).offset();
var width = $(tableCell).innerWidth();
var height = $(tableCell).innerHeight();
return {
x: offset.left + width / 2,
y: offset.top + height / 2
}
}
// draws an arrow on the document from the start to the end offsets
function drawArrow(start, end) {
// create a canvas to draw the arrow on
var canvas = document.createElement('canvas');
canvas.width = $('body').innerWidth();
canvas.height = $('body').innerHeight();
$(canvas).css('position', 'absolute');
$(canvas).css('pointer-events', 'none');
$(canvas).css('top', '0');
$(canvas).css('left', '0');
$(canvas).css('opacity', '0.85');
$('body').append(canvas);
// get the drawing context
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'steelblue';
ctx.strokeStyle = 'steelblue';
// draw line from start to end
ctx.beginPath();
ctx.moveTo(start.x, start.y);
ctx.lineTo(end.x, end.y);
ctx.lineWidth = 2;
ctx.stroke();
// draw circle at beginning of line
ctx.beginPath();
ctx.arc(start.x, start.y, 4, 0, Math.PI * 2, true);
ctx.fill();
// draw pointer at end of line (needs rotation)
ctx.beginPath();
var angle = Math.atan2(end.y - start.y, end.x - start.x);
ctx.translate(end.x, end.y);
ctx.rotate(angle);
ctx.moveTo(0, 0);
ctx.lineTo(-10, -7);
ctx.lineTo(-10, 7);
ctx.lineTo(0, 0);
ctx.fill();
// reset canvas context
ctx.setTransform(1, 0, 0, 1, 0, 0);
return canvas;
}
// finds the center of the start and end cells, and then calls drawArrow
function drawArrowOnTable(table, startRow, startColumn, endRow, endColumn) {
drawArrow(
getCellCenter($(table), startRow, startColumn),
getCellCenter($(table), endRow, endColumn)
);
}
// draw an arrow from (1, 0) to (2, 4)
drawArrowOnTable('table', 1, 0, 2, 4);
table, td {
border-collapse: collapse;
}
td {
border: 1px solid #ddd;
padding: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>D1</td>
<td>E1</td>
</tr>
<tr>
<td>A2</td>
<td>B2</td>
<td>C2</td>
<td>D2</td>
<td>E2</td>
</tr>
<tr>
<td>A3</td>
<td>B3</td>
<td>C3</td>
<td>D3</td>
<td>E3</td>
</tr>
</table>
<pre>drawArrowOnTable('table', 1, 0, 2, 4);</pre>
</body>
</html>