【问题标题】:Div overlay canvas, mouseoverDiv 覆盖画布,鼠标悬停
【发布时间】:2015-07-26 06:28:12
【问题描述】:

我有画布区域,我可以在其中添加一些图像。 而且我想将整个画布切割成部分并只下载图像的一部分。

如果我将 div 与颜色覆盖画布放在一起,我就无法在里面移动我的元素。 但我想向用户显示已选择并将下载的区域。

是否可以显示一些 div 覆盖画布并使用画布进行管理?

如果我的 div 不可见,因为 z-index 比我的画布图像低,我怎么能监听 mouseover 事件?

【问题讨论】:

  • 我已经发布了一个答案,展示了如何使用覆盖画布来“着色”图像的当前选定部分。祝你的项目好运!

标签: javascript jquery canvas hover


【解决方案1】:

您无需尝试为您的 div 着色,而是使用图像画布顶部的第二个(覆盖)画布来为下面的图像画布的所需部分着色。

  • 定义一个表示画布每个部分(矩形)的 javascript 对象。
  • 在您的图像画布上放置第二个覆盖画布,并使用 CSS 告诉它不要发出事件:pointer-events:none
  • 在鼠标移动时,用半透明颜色填充鼠标下方的覆盖画布部分。

这是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var overlay=document.getElementById("overlay");
var octx=overlay.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }



var selectedPart=1;
var parts=[];

var img=new Image();
img.onload=start;
img.src='https://dl.dropboxusercontent.com/u/139992952/multple/sailboatSmall.png';
function start(){

  cw=canvas.width=overlay.width=img.width;
  ch=canvas.height=overlay.height=img.height;

  octx.font='18px verdana';
  octx.textAlign='center';
  octx.textBaseline='middle';
  octx.lineWidth=0.50;
  octx.fillStyle='red';
  octx.globalAlpha=0.10;

  parts.push({x:0,y:0,w:cw/3,h:ch/2});
  parts.push({x:cw/3,y:0,w:cw/3,h:ch/2});
  parts.push({x:cw*2/3,y:0,w:cw/3,h:ch/2});
  parts.push({x:0,y:ch/2,w:cw/2,h:ch/2});
  parts.push({x:cw/2,y:ch/2,w:cw/2,h:ch/2});

  ctx.drawImage(img,0,0);

  $("#canvas").mousemove(function(e){handleMouseMove(e);});
}

function handleMouseMove(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  var x=parseInt(e.clientX-offsetX);
  var y=parseInt(e.clientY-offsetY);

  for(var i=0;i<parts.length;i++){
    var p=parts[i];
    if(x>p.x && x<p.x+p.w && y>p.y && y<p.y+p.h){
      if(i==selectedPart){return;}
      selectedPart=i;
      octx.clearRect(0,0,cw,ch);
      octx.fillRect(p.x,p.y,p.w,p.h);
    }
  }
}
body{ background-color:white; }
#container{position:relative;}
#canvas,#overlay{position:absolute;}
#overlay{pointer-events:none;border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Move mouse over image parts</h4>
<div id=container>
  <canvas id="canvas" width=300 height=300></canvas>
  <canvas id="overlay" width=300 height=300></canvas>
</div>

【讨论】:

  • div 是不可见的。我想用不透明度设置颜色。有可能吗?
  • 对不起。使用指针事件:无我无法检测到事件 onmouseevent。
  • @iiylll 请原谅。我想我误解了你的问题——我以为你想让画布响应事件,同时在画布上放置 div。你能解释一下你需要什么吗?
  • 我有 Photoshop 中的尺子。我可以用它把整个画布切成小块,然后通过单击画布的特定部分分别下载它们。我想在鼠标所在的那部分用颜色+不透明度填充画布。
猜你喜欢
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 2018-12-06
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
相关资源
最近更新 更多