HTML5画布坐标用铬处理

HTML5 Canvas Coordinates Chnged in chrome

本文关键字:处理 坐标 布坐标 HTML5      更新时间:2024-03-31

我有一个Sharepoint页面,我想在其中显示一个带有方框的层次图。根据我的要求,这些框应该作为链接到同一网站中的其他共享点页面。

由于sharepoint的默认设计器工具不支持设计这样的图表,所以我创建了一个带有html5画布和我想要的元素的页面。在画布内部,我创建了一些框和线来连接它们。我在盒子里添加了文字。然后,我使用鼠标监听器来检查鼠标指针是否悬停在框上,如果是,则更改指针图标和要重定向到的链接。

我通过"编辑源代码"在sharepoint页面中添加了画布标记,并使用"嵌入代码"添加了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动态计算)。