我做了一个非常粗略的例子,说明我是怎么做的.它应该让你在正确的轨道上:
我将class line用于hoverable元素,并使用data-id属性作为相应的元素.
HTML:
This is my text with this very important word
...
o asf isj biojso jo f ad f
jQuery的:
$('.line').hover(function () {
var $t = $(this);
var $i = $('#' + $t.data('id'));
// find offset positions for the word (t = this) and image (i)
var ot = {
x: $t.offset().left + $t.width() / 2,
y: $t.offset().top + $t.height() / 2
};
var oi = {
x: $i.offset().left + $i.width() / 2,
y: $i.offset().top + $i.height() / 2
};
// x,y = top left corner
// x1,y1 = bottom right corner
var p = {
x: ot.x < oi.x ? ot.x : oi.x,
x1: ot.x > oi.x ? ot.x : oi.x,
y: ot.y < oi.y ? ot.y : oi.y,
y1: ot.y > oi.y ? ot.y : oi.y
};
// create canvas between those points
var c = $('').attr({
'width': p.x1 - p.x,
'height': p.y1 - p.y
}).css({
'position': 'absolute',
'left': p.x,
'top': p.y,
'z-index': 1
}).appendTo($('body'))[0].getContext('2d');
// draw line
c.strokeStyle = '#f00';
c.lineWidth = 2;
c.beginPath();
c.moveTo(ot.x - p.x, ot.y - p.y);
c.lineTo(oi.x - p.x, oi.y - p.y);
c.stroke();
}, function () {
$('canvas').remove();
});
演示: