<script>
//创建一个画板
let canvas = document.createElement('canvas');
canvas.width = 500;
canvas.height = 500;
document.body.appendChild(canvas);
let cxk = canvas.getContext('2d');
let deg = Math.PI / 180//定义一个初始度数
let data = [2, 7, 9, 6, 4, 3];
let totle = data.reduce(function (pre, cur) {//数据求和
return pre + cur;
})
let color = ['red', 'green', 'pink', 'yellow', 'blue', 'purple']
//封装一个函数
draw()
function draw(size) {
let sdeg = 0;
for (var i = 0; i < data.length; i++) {
let cdeg = data[i] / totle * 360 * deg;
cxk.save()
cxk.beginPath();
cxk.fillStyle = color[i];
cxk.moveTo(250, 250);
cxk.arc(250, 250, 100, sdeg, sdeg + cdeg);
if (size && cxk.isPointInPath(size.x, size.y)) {
cxk.fillStyle = 'black';
cxk.moveTo(250, 250);
cxk.arc(250, 250, 120, sdeg, sdeg + cdeg)
}
cxk.fill();
cxk.restore();
sdeg += cdeg
}
}
canvas.addEventListener('mousemove', function (e) {
let mx = event.offsetX;
let my = event.offsetY;
cxk.clearRect(0, 0, 500, 500);
draw({
x: event.offsetX,
y: event.offsetY
})
})
</script>
网友评论