[英]On mouseover overlay image onto canvas
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中添加它的选项。
可视化:
有没有简单的方法可以做到这一点? 布朗尼指向图像是否可以淡入和淡出。
基本思想是将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>
这是工作的JSFiddle 。
将画布包装在有位置的外部容器中,然后将图标相对于外部包装器放置在所需的任何位置
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
}
您可以使用.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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.