function() {
var graph = document.getElementById('canvas');
if (graph.getContext){
var g = graph.getContext('2d');
g.strokeStyle = '#000';
g.beginPath();
for (var i = 0, l = a.length; i < l; i++) {
g.arc((i + 1) * 100,a[i],3,0,Math.PI*2,true);
g.fill();
g.lineTo((i + 1) * 100,a[i]);
}
g.fillStyle="black";
g.stroke();
g.closePath();
想做出鼠標滑動到點上時,有一個信息框顯示出來,大神們幫我!
用這個吧,忘記計算canvas的位置了
<style>
#note{position:absolute;display:none;border:solid 1px #000;background:#fff}
</style>
<canvas id="canvas" style="border:solid 1px #000;margin:100px 0 0 100px;" width="1000"></canvas>
<div id="note"></div>
<script>
var a = [10, 20, 30, 40, 50, 20, 30, 40],note=document.getElementById('note');
var c = document.getElementById('canvas');
function getLeftRight(o) {
var p = { x: o.offsetLeft, y: o.offsetTop };
while (o = o.offsetParent) { p.x += o.offsetLeft; p.y += o.offsetTop; }
return p;
}
function hitCheck(x, y, point, r) {//檢查是否移動到點上,直接按照正方形檢查了,圓形比較麻煩
var x1 = point.x, y1 = point.y;
return x1 + r > x && x1 - r < x && y1 + r > y && y1 - r < y;
}
if (c.getContext) {
var g = c.getContext('2d');
var points = [];//原點圓心集合
var r = 3;//半徑
var cP = getLeftRight(c);//獲取canvas對象位置
for (var i = 0, l = a.length; i < l; i++) {
points[i] = { x: (i + 1) * 100, y: a[i] };
g.beginPath();
g.moveTo(i * 100, i - 1 < 0 ? 0 : a[i - 1]);
g.lineTo((i + 1) * 100, a[i]);
g.arc((i + 1) * 100, a[i], r, 0, Math.PI * 2, true);
g.fill();
g.stroke();
g.closePath()
}
var timer;
c.addEventListener('mousemove', function (e) {
clearTimeout(timer);
var x = e.clientX, y = e.clientY;
timer = setTimeout(function () {
for (var i = 0; i < points.length; i++)
if (hitCheck(x - cP.x, y - cP.y, points[i], r)) {
note.style.display = 'block';
note.style.left = points[i].x +cP.x+ r + 1 + 'px';
note.style.top = points[i].y + cP.y + r + 1 + 'px';
note.innerHTML = 'X:' + points[i].x + ' Y:' + points[i].y;
return
}
note.style.display = 'none';
}, 100);
}, false);
}
</script>