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();
当鼠标悬停在画布上时,我想将图像(&#34; close_icon.png&#34;)叠加到右上角的画布上,并在鼠标离开画布时再次移除。< / p>
Jquery可用,但我找不到在jsfiddle中添加它的选项。
可视化:
有没有简单的方法来实现这一目标?布朗尼指出图像是否可以淡入和淡出。
答案 0 :(得分: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();
&#13;
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;
}
&#13;
<div>
<canvas id="myCanvas" width="200" height="200"></canvas>
<img src="http://placehold.it/30x30">
</div>
&#13;
此处&#39; a working JSFiddle。
答案 1 :(得分: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 强>
答案 2 :(得分:0)
您可以使用<span class="cross">
添加.hover
:
$("#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);
}