代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.canvas {
border: 1px solid #333;
}
</style>
</head>
<body>
<canvas class="canvas" width="300" height="300"></canvas>
<script>
function Canvas(element, arr, data) {
this.element = element;
if (data && data instanceof Object) {
//ES6语法,合并对象。
let { x = 0 } = Object.assign({}, data);
this.x = x;
let { y = 0 } = Object.assign({}, data);
this.y = y;
let { r = 0 } = Object.assign({}, data);
this.r = r;
}
this.arr = arr;
//定义数组数的总和
this.sum = null;
//起始坐标
this.start = 0;
//终止坐标
this.end = 0;
this.main();
}
Canvas.prototype = {
constructor: Canvas,
//定义调用函数,供上面使用
main() {
this.getelement();
this.draw();
},
//定义获取元素的函数
getelement() {
this.canvas = document.querySelector(this.element);
this.ctx = this.canvas.getContext('2d');
this.width = this.canvas.width;
this.height = this.canvas.height;
},
//绘制函数
draw() {
for (let i = 0; i < this.arr.length; i++) {
this.sum += this.arr[i]
}
for (let i = 0; i < this.arr.length; i++) {
this.rgb = this.randomcolor().join(',');
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y);
this.end += this.arr[i] / (this.sum / 2);//终止角度
this.ctx.arc(this.x, this.y, this.r, this.start * Math.PI, this.end * Math.PI);
this.ctx.fillStyle = `rgb(${this.rgb})`;
this.ctx.fill();
this.ctx.closePath();
this.start += this.arr[i] / (this.sum / 2);//起始角度
}
},
//取随机颜色的函数
randomcolor() {
let colorarr = [];
let result = 255 - 0 + 1;
for (var j = 0; j < 3; j++) {
colorarr.push(Math.floor(Math.random() * result + 1))
}
return colorarr;
},
}
//调用
new Canvas('.canvas', [20, 30, 44, 88, 60, 77, 80], {
x: 150,
y: 150,
r: 100
})
</script>
</body>
</html>
写的比较简单,求大佬手下留情。
求出数组数的总和,然后拿数组中的每个数除以总和,求出每个的比例。
下一个的开始角度是上一个的结束角度。