如上图所示,如何实现鼠标移动到两个分开的圆环时给当前圆环添加阴影效果,我现在实现的效果是鼠标hover时,高亮了整个canvas,请问各位大佬如何解决该问题?
我实现的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas环形图01</title>
<style type="text/css">
#canvas {
margin: 100px auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="200" height="300"></canvas>
<script type="text/javascript">
function draw(options) {
var oBox = document.getElementById(options.id);
var ctx = oBox.getContext('2d');
var sCenter = oBox.width / 2;
var txtY01 = sCenter - 10;
var txtY02 = sCenter + 10;
var cWidth = oBox.width;
var cHeight = oBox.height;
ctx.clearRect(0, 0, cWidth, cHeight);
var cBegain = 0;
var cEnd = Math.PI * 2;
ctx.textAlign = 'center';
ctx.font = 'normal normal 16px Microsoft YaHei';
ctx.fillStyle = '#666';
ctx.fillText(options.text[0], sCenter, txtY01);
ctx.textAlign = 'center';
ctx.font = 'normal normal 14px Microsoft YaHei';
ctx.fillStyle = '#ccc';
ctx.fillText(options.text[1], sCenter, txtY02);
ctx.lineCap = options.lineCap;
ctx.strokeStyle = options.color;
ctx.lineWidth = options.lineWidth[0];
ctx.beginPath();
const begain01 = cBegain+options.gap[0];
const end01 = (cEnd * options.angle[0]) - cBegain - options.gap[0];
ctx.strokeStyle = '#A8B9C9';
ctx.arc(sCenter, sCenter, options.radius[0], begain01, end01, false);
ctx.stroke();
// 环形阴影
ctx.shadowColor = "#FFD38E";
ctx.shadowOffsetX = options.shadow ? 5 : 0;
ctx.shadowBlur = 8;
ctx.lineCap = options.lineCap;
ctx.strokeStyle = options.color;
ctx.lineWidth = options.lineWidth[1];
ctx.beginPath();
const begain02 = cBegain-options.gap[1];
const end02 = -(cEnd * options.angle[1]) + options.gap[1];
ctx.strokeStyle = options.color;
ctx.arc(sCenter, sCenter, options.radius[1], begain02, end02, true);
ctx.stroke();
}
draw({
id: 'canvas',
color: '#FF9C00',
angle: [0.3, 0.7],
radius: [80, 80],
lineWidth: [20, 20],
text: [1000, '发送总人数'],
gap: [0.02, 0.02],
shadow: false
});
var oBox = document.getElementById('canvas');
oBox.onmousemove = (e) => {
draw({
id: 'canvas',
color: '#FF9C00',
angle: [0.3, 0.7],
radius: [80, 80],
lineWidth: [20, 20],
text: [1000, '发送总人数'],
gap: [0.02, 0.02],
shadow: true
});
}
</script>
</body>
</html>
canvas
不像svg
,它对外是一个整体,你只能通过具体的坐标数据,自己计算鼠标位于内部哪些“元素”上面。而具体的算法,也不是那么直观的,可以去找找 echarts 实现方面的东西参考。