chrome中的HTML5画布坐标

迪伦德

我有一个Sharepoint页面,我想在其中显示带有框的层次结构图。根据我的要求,这些框应作为指向同一站点中其他Sharepoint页面的链接。

由于sharepoint的默认设计器工具不支持设计此类图表,因此我创建了一个带有html5 canvas及其想要的元素的页面。在画布内部,我创建了几个框和线来连接它们,并在框内添加了文本,然后使用鼠标侦听器检查鼠标指针是否悬停在一个框上,如果是,则更改指针图标和要重定向的链接到。

我通过“编辑源”在共享点页面内添加了画布标签,并使用“嵌入代码”添加了javascript部分

现在,该代码可以在IE和Firefox中完美运行。在chrome中,虽然根据我在代码中给出的坐标绘制了框,线和文本,但是当我将鼠标悬停在它们上面时,它会为不同大小的浏览器提供不同的鼠标侦听器坐标。因此,鼠标指针在正确的位置,即:在盒子上。

在Firefox或IE中不会发生这种情况。当鼠标指针越过框并完美链接到页面时,它们将更改鼠标指针。

为什么我使用Chrome时会改变?以及为什么它只影响鼠标侦听器的坐标。

这是我使用的代码。(我已删除其绘制其它框的重复部分)在同样的jsfiddle

    ​<canvas id="myCanvas" height="500" width="960" style="border: 1px solid;">​<img src="" alt=""/> </canvas>​ 

<script>
var canvas = document.getElementById("myCanvas");
var ctx;

    var rNBDX = 50;     var rNBDY = 150;            
    var rectWidth = 200; 
    var rectHeight = 100;
    var cornerRadius = 20;

    var linkNBD="https://google.com";
    var textNBD1 ="Google"; 
    var linkHeight=20;
    var linkNum = 0;

function draw(){
  canvas = document.getElementById("myCanvas");
  if(canvas.getContext){

    ctx=canvas.getContext("2d");
    //Drawing Lines
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#000000';
    ctx.moveTo(380, 100);
    ctx.lineTo(380, 125);
    ctx.stroke();

    //Drawing Rectangles
    ctx.fillStyle="#0b61d0";
    ctx.strokeStyle="#0b61d0";
    ctx.lineJoin = "round";
    ctx.lineWidth = cornerRadius;

    ctx.strokeRect(rNBDX+(cornerRadius/2), rNBDY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
    ctx.fillRect(rNBDX+(cornerRadius/2), rNBDY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);

    //Drawing the Texts
    ctx.font='24px Segoe UI Light';
    ctx.fillStyle = "#FFFFFF";  
    ctx.fillText(textNBD1,(rNBDX+rectWidth/2)-(ctx.measureText(textNBD1).width)/2,rNBDY+rectHeight/2);

    //Add mouse listeners
    canvas.addEventListener("mousemove", on_mousemove, false);
    canvas.addEventListener("click", on_click, false);
  }
}

function on_mousemove (ev) {
  var x, y;

  if (ev.layerX || ev.layerX == 0) {
    x = ev.layerX;
    y = ev.layerY;
  }
  x-=canvas.offsetLeft;
  y-=canvas.offsetTop;

  if(x>=rNBDX && x <= (rNBDX + rectWidth) && y>=rNBDY && y<= (rNBDY+rectHeight)){
      document.body.style.cursor = "pointer";
      linkNum=1;
  }
  else{
      document.body.style.cursor = "";
  }
}
function on_click(e) { 
  switch (linkNum)
    {
    case 1:
        window.location = linkNBD;
        break;
    }
}
draw();
</script>
用户名

尝试像这样调整鼠标坐标:

function on_mousemove (ev) {

  var x, y,
      rect = canvas.getBoundingClientRect();

  x = ev.clientX - rect.left + 1;
  y = ev.clientY - rect.top + 1;
  ...

您将不得不添加(如示例中所示)左/上边框的宽度,尽管其中getBoundingClientRect不包括这些宽度(您可以使用getComputedStylegetPropertyValue动态计算边框的宽度)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章