嘿,我正在尝试在 Canvas 点上创建工具提示。我有一个非常简单的三 Angular 形,我想在他的点的每个边缘上创建一个工具提示。这意味着我需要 3 个工具提示来表示三 Angular 形的 3 个点。 这是我到目前为止所取得的成就,我已经成功地将监听器添加到 mosueover 和 mosueclick 中。 我可以为每个点添加一个工具提示吗?如果可以,我可以将这样的工具提示添加到一个圆上吗?
更新:
我已经浏览了以下链接:tooltip canvas并在我的代码上实现它。 问题是,工具提示没有显示在三 Angular 形中的每个点上,并且存在故障。 我已经更新了代码,请查看一下。 这是新增内容:
if (ctx.isPointInPath(mouse.x, mouse.y)) {
$tip.text("I have a tip for you:(x:" + mouse.x + "y:" + mouse.y + ")");
$tip.css({
left: e.clientX + 3,
top: e.clientY - 18
}).show();
问题是,当我在三 Angular 形内部单击时,工具提示看起来距离当前位置很远。
$(function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var triangle = [{
x: 58,
y: 845
}, {
x: 984,
y: 845
}, {
x: 521,
y: 41
}];
drawTriangle(triangle);
$tip = $('#tip');
$tip.hide();
// define tooltips for each data point
function drawTriangle(t) {
ctx.beginPath();
ctx.moveTo(t[0].x, t[0].y);
ctx.lineTo(t[1].x, t[1].y);
ctx.lineTo(t[2].x, t[2].y);
ctx.closePath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.stroke();
}
var canvasPosition = {
x: canvas.offsetLeft,
y: canvas.offsetTop
};
canvas.addEventListener("click", function(e) {
e.preventDefault();
// use pageX and pageY to get the mouse position
// relative to the browser window
var mouse = {
x: e.pageX - canvasPosition.x,
y: e.pageY - canvasPosition.y
}
if (ctx.isPointInPath(mouse.x, mouse.y)) {
$tip.text("I have a tip for you:(x:" + mouse.x + "y:" + mouse.y + ")");
$tip.css({
left: e.clientX + 3,
top: e.clientY - 18
}).show();
}
});
})
#tip {
position: absolute;
background: white;
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canvas-wrapper">
<canvas id="canvas" width=1024 height=980></canvas>
<div id=tip>Tooltip</div>
</div>
最佳答案
您更新的代码几乎可以工作,但您需要考虑窗口滚动。
您可以通过订阅 window.onscroll
事件然后更新 Canvas 偏移变量来做到这一点。调整窗口大小也会影响 Canvas 的相对位置,因此还要更新 Canvas 偏移变量以响应 window.onresize
事件。
// create vars that hold the canvas offset vs the window
var offsetX,offsetY;
reOffset();
// subscribe to scroll & resize events
// and recalculate the offset
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }
// calculate the current canvas offset vs the window
function reOffset(){
var BB=canvas.getBoundingClientRect();
offsetX=BB.left;
offsetY=BB.top;
}
关于javascript - 如何为 Canvas 点创建简单和高级的工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36741916/