您无法使用 CSS 或 jQuery 控制 html 画布绘图。
DOM 元素可以在悬停时触发事件,因为它们是对象,浏览器知道它们的位置并为您跟踪鼠标。
与 DOM 元素不同,画布绘图只是画布上的像素,而不是对象。绘制完成后,浏览器不跟踪像素,像素无法触发任何事件。
通常的做法是使用 javascript 在画布绘图中“模拟”悬停行为。
由于画布绘图只是像素,要改变绘图的外观,您必须实际擦除像素并使用所需的效果重新绘制。所以在你的情况下:
在模拟悬停时:
关于模拟模糊:
如果你想在 html 画布上绘制动画,你还必须使用 javascript 手动完成:
逐步更改圆形属性(稍微增加大小或稍微改变颜色);
擦除画布。
以新的增量变化状态绘制圆圈。
重复 #1 直到动画完成。
提示:使用 requestAnimationFrame 可以为您的动画提供高性能。皇家空军允许您创建与浏览器刷新协调的动画循环以提供良好的性能。
示例代码和演示:http://jsfiddle.net/m1erickson/h3Hc7/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#canvas{border:1px solid red;}
</style>
<script>
$(function(){
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var scrollX=$canvas.scrollLeft();
var scrollY=$canvas.scrollTop();
// create an object that represents the circle
var circle={
cx:95,
cy:50,
radius:20,
blurColor:"#FF8C00",
hoverColor:"red",
wasInside:false,
}
// draw the circle on the canvas the first time
drawCircle(circle,false);
// draw a circle on the canvas in a color that represents its hover state
function drawCircle(circle,isInside){
ctx.beginPath();
ctx.arc(circle.cx,circle.cy,circle.radius, 0, 2 * Math.PI);
ctx.fillStyle = isInside ? circle.hoverColor : circle.blurColor;
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = '#2d2d2d';
ctx.stroke();
// save the hover status of this circle
circle.wasInside=isInside;
}
function handleMouseMove(e){
// tell the browser that we're handling this event
e.preventDefault();
e.stopPropagation();
// calculate the mouse position
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// calculate if the mouse is currently inside the circle
var dx=mouseX-circle.cx;
var dy=mouseY-circle.cy;
var isInside=dx*dx+dy*dy<=circle.radius*circle.radius;
// if the mouse has either entered or exited the circle
// then erase and redraw the circle to reflect its current
// hover state
if( isInside && !circle.wasInside ){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawCircle(circle,isInside);
}else if( !isInside && circle.wasInside ){
ctx.clearRect(0,0,canvas.width,canvas.height);
drawCircle(circle,isInside);
}
}
// listen for mousemove events
$("#canvas").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>