簡體   English   中英

Div覆蓋畫布,鼠標懸停

[英]Div overlay canvas, mouseover

帆布區與divs

我有畫布區,我可以添加一些圖像。 我想將整個畫布切割成零件並僅下載圖像的一部分。

如果我把div與彩色覆蓋畫布,我不能移動我的元素。 但我想向用戶顯示哪些區域已被選中並將被下載。

是否可以顯示一些divs overlay canvas並使用canvas進行管理?

如果沒有,我怎么能聽到我的div看不見的鼠標懸停事件,因為z-index比我的畫布圖像低?

您可以在圖像畫布頂部使用第二個(疊加)畫布,而不是嘗試為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>px && x<p.x+pw && y>py && y<p.y+ph){ if(i==selectedPart){return;} selectedPart=i; octx.clearRect(0,0,cw,ch); octx.fillRect(px,py,pw,ph); } } } 
 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM