效果展示
代码实现:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body{
text-align: center;
padding-top: 100px;
}
.content{
display: none;
position: absolute;
background: white;
font-weight: bold;
border-radius: 10px;
padding: 10px;
}
.cake{
position: absolute;
}
.total{
position: relative;
width: 600px;
height: 600px;
margin: auto;
}
</style>
</head>
<body>
<h1>鼠标移动到饼图可以动态显示tip</h1>
<div class="total">
<canvas id="cake" width="600" height="600">
</canvas>
<div class="content" id="contentid">
<div class="title">
卖家
</div>
<div class="num">
数量:88
</div>
</div>
</div>
<script>
var canvas = document.getElementById('cake');
var tip = document.getElementById('contentid');
var title = document.querySelector('.title');
var num = document.querySelector('.num');
var context = canvas.getContext('2d');
context.fillStyle="#E0FFFF";
context.fillRect(0,0,canvas.width,canvas.height);
//角度数组 30 60 90 120 60
var radiusArr = [
[0, Math.PI/6, '#FF00FF'],
[(Math.PI/6), (Math.PI/2), '#EEEE00'],
[(Math.PI/2), Math.PI, '#C1FFC1'],
[Math.PI, (Math.PI+Math.PI*2/3), '#9AC0CD'],
[(Math.PI+Math.PI*2/3), 2*Math.PI, '#40E0D0']
]
for(var i = 0 ; i < radiusArr.length; i++ ){
context.fillStyle= radiusArr[i][2];
context.beginPath();
//定义起点
context.moveTo(300,200);
context.arc(300, 200, 150, radiusArr[i][0], radiusArr[i][1], false);
context.fill();
context.closePath();
context.beginPath();
//定义起点
context.moveTo(50+i*100,500);
context.arc(50+i*100,500, 10, 0, 2*Math.PI , false);
context.fill();
context.closePath();
//编写文本
context.font='normal bold 16px Arial,sans-serif ';
context.fillStyle= '#0A0A0A';
context.fillText('店家'+(i+1), 50+i*100+20, 510);
}
//绘画底部导航栏
canvas.onmousemove = function(e){
//在圆内
var x = e.offsetX
var y = e.offsetY
//计算距离
var c = Math.sqrt(Math.pow(300-x,2)+Math.pow(200-y,2));
if(c<150){
tip.style.display = 'block';
tip.style.top = e.offsetY+'px';
tip.style.left = e.offsetX+'px';
//计算角度
var curradius = Math.atan2(200-y,x-300);
if(curradius < 0 ){
curradius = -curradius;
}else{
curradius = 2*Math.PI - curradius;
}
if(0<= curradius && curradius<Math.PI/6){
title.innerText = '店家1';
num.innerText = '买卖数量:81';
}else if(Math.PI/6 <= curradius && curradius < (Math.PI/2)){
title.innerText = '店家2';
num.innerText = '买卖数量:802';
}else if((Math.PI/2) <= curradius && curradius < Math.PI){
title.innerText = '店家3';
num.innerText = '买卖数量:8003';
}else if(Math.PI <= curradius && curradius < (Math.PI+Math.PI*2/3)){
title.innerText = '店家4';
num.innerText = '买卖数量:804';
}else {
title.innerText = '店家5';
num.innerText = '买卖数量:8055';
}
}else{
tip.style.display = 'none';
}
}
</script>
</body>
</html>