为什么当我激活画布叠加层时,我的图像和画布叠加层会向左跳?

时间:2021-03-05 19:44:13

标签: javascript jquery bootstrap-4 html5-canvas

我在 Django 项目中使用 Bootstrap 4。我有一个带有图像和画布覆盖的页面。覆盖层用于指出图像上的某些伪影(即带有一些“洞”的深色覆盖层,显示底层图像和一些文本)。通过将鼠标悬停在按钮上来激活叠加层。该图像还被一个锚标记包围,以将其链接到一个引导灯箱,该灯箱显示图像的较大版本。

我发现灯箱链接弄乱了画布覆盖,所以我添加了一些 js 代码来换出两个 div (id="locate_faces") - 一个带有图像和画布,另一个带有图像和灯箱链接。如果鼠标悬停在按钮上,带有图像和画布的 div 被交换到页面中,带有图像和灯箱链接的 div 被交换;当鼠标离开按钮时,带有图像和灯箱链接的 div 被交换到页面中,带有图像和画布的 div 被换出。

一些代码片段 - 此 jsfiddle 中有一个工作项目:

页面加载和鼠标悬停在按钮上时的 div“locate_faces”:

<div id="locate_faces">
   <img  src="https://natures-spa.com/wp-content/uploads/2017/09/biodynamic-facial-package-woman-in-lavender-field-blue-sky-700px-wide-lr.jpg" id='img1' class="top-center img-fluid" style="position:relative;z-index:10"/>
   <canvas id="overlay" width="610" height="550" class="top-center img-fluid" style="z-index:9900;position:absolute"></canvas>
</div>

页面加载后的div“locate_faces”,当鼠标离开按钮时被换入:

<div id="locate_faces">
    <a href="https://natures-spa.com/wp-content/uploads/2017/09/biodynamic-facial-package-woman-in-lavender-field-blue-sky-700px-wide-lr.jpg" data-toggle="lightbox" data-gallery="gallery" class="col-md-4" id="l_box">
        <img  src="https://natures-spa.com/wp-content/uploads/2017/09/biodynamic-facial-package-woman-in-lavender-field-blue-sky-700px-wide-lr.jpg" id="img1"  width="610" height="550" class="top-center img-fluid" style="position:relative;z-index:10;"/>
    </a>
</div>

画布代码:

  image = document.getElementById("img1");
  position = $("#img1").position();
  canvas  = document.getElementById("overlay");
  
  canvas.width = image.width;
  canvas.height = image.height;

  context = canvas.getContext("2d");
  canvas.style.left = position.left + "px";
  canvas.style.top = position.top + "px";
  canvas.style.width = image.width + "px";
  canvas.style.height = image.height + "px";
  context.fillStyle = "rgba(0, 0, 0, 0)";

  // detach this code from the page and add in the lightbox code
  my_canvas = $("#locate_faces").detachTemp();

代码有效(*),除了当我将鼠标悬停在按钮上时,图像和画布向左跳,然后在鼠标停止悬停在按钮上时跳回(请参阅 jsfiddle)。我认为问题可能是在图像和画布元素中使用了 position: relativeposition: absolute,但我尝试了相对和绝对的所有组合,但没有任何改进。

当画布被激活时,我很想摆脱向左跳跃的图像。是什么导致了跳跃,我该如何摆脱它?

谢谢,

标记

0 个答案:

没有答案