2016-01-23 93 views
0

https://jsfiddle.net/c309a2wo/在鼠标悬停覆盖图像投影到画布

HTML

<canvas id="myCanvas" width="200" height="200"></canvas> 

的javascript

var canvas = document.getElementById("myCanvas"); 

var ctx = canvas.getContext('2d'); 

ctx.fillStyle = "rgb(0,255,255)"; 
ctx.fillRect(0, 0, canvas.width, canvas.height); 

ctx.beginPath(); 
ctx.fillStyle = "rgb(200,0,0)"; 
ctx.arc(canvas.width/2, canvas.height/2, 50, 0, Math.PI*2); 
ctx.fill(); 

我想覆盖的图像( “close_icon.png”)到当鼠标悬停在画布上时右上角的画布将被移除,并在画布上再次移除鼠标离开画布。

Jquery可用,但我找不到在jsfiddle中添加它的选项。

可视化:

Current

Desired

是否有一个简单的方法来做到这一点?布朗尼指出,如果图像可以淡入淡出。

回答

3

的基本思想是在一个容器元素来包装你canvas,然后添加仅在:hover上显示的容器中的图像。

var canvas = document.getElementById("myCanvas"); 
 

 
var ctx = canvas.getContext('2d'); 
 

 
ctx.fillStyle = "rgb(0,255,255)"; 
 
ctx.fillRect(0, 0, canvas.width, canvas.height); 
 

 
ctx.beginPath(); 
 
ctx.fillStyle = "rgb(200,0,0)"; 
 
ctx.arc(canvas.width/2, canvas.height/2, 50, 0, Math.PI*2); 
 
ctx.fill();
div { 
 
    position: relative; 
 
    display: inline-block; 
 
    } 
 

 
    canvas { 
 
    position: relative; 
 
    z-index: -1; 
 
    } 
 

 
    img { 
 
    position: absolute; 
 
    top: 4%; 
 
    right: 4%; 
 
    opacity: 0; 
 
    z-index: 2; 
 
    -webkit-transition: opacity 0.4s linear; 
 
    transition: opacity 0.4s linear; 
 
    } 
 

 
    div:hover img { 
 
    opacity: 1; 
 
    }
<div> 
 
<canvas id="myCanvas" width="200" height="200"></canvas> 
 
<img src="http://placehold.it/30x30"> 
 
</div>

Here'a working JSFiddle

+0

已更新为淡入/淡出。 –

+0

谢谢。宁愿不添加额外的div,但这是一个非常简洁的解决方案,所以我一定会使用它! – AndrewB

0

您可以使用.hover添加<span class="cross">

$("#myCancas").hover(function(){$(this).append($("<span class="cross"></span>"));}); 

,然后设置样式,使用CSS:

span.cross{ 
    display: block; 
    width: 10px; 
    height: 10px; 
    background-image: url(path/to/cross/jpg); 
} 
1

裹帆布它在具有位置外部容器,那么无论你想相对于外包装

HTML

<div id="canvas-wrap"> 
    <span id="canvas-icon"></span> 
    <canvas id="myCanvas" width="200" height="200"></canvas> 
</div> 

CSS

#canvas-wrap{ 
    position:relative; 
    width:200px; height:200px 
} 
#canvas-icon{ 
    background:yellow; 
    width:32px; 
    height:32px; 
    position:absolute; 
    top:10px; 
    right:10px; 
    z-index:10; 
    display:none 
} 
#canvas-wrap:hover #canvas-icon{ 
    display:block 
} 

可以定位图标DEMO