
image.png
- 核心知识点
扇形需要一个起始点,半径,起始弧度和结束弧度
- 相关知识点
beginPath : 开始一段新路径
save: 这一时刻的设置会放到一个暂存栈中.保存之后可以继续修改上下文
restore:这个方法主要是从暂存中取出并恢复之前保存的设置.保存多个,需要一步一步的释放
moveTo:不绘制先,只移动光标
arc:已x,y为圆心,已 r 为半径,其实位置和结束位置绘制一段圆弧
fillStyle:填充 yanse
fill:填充
最简单的圆弧如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>饼图</title>
<style>
body {
margin: 0;
overflow: hidden
}
#canvas {
background: antiquewhite;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script>
const [width,height]=[window.innerWidth,window.innerHeight];
const canvas = document.getElementById("canvas")
canvas.width = width
canvas.height = height
const ctx = canvas.getContext("2d")
class Sector {
constructor(radius = 200, startAngle = 0, endAngle = Math.PI / 2, color = 'chocolate') {
this.radius = radius
this.startAngle = startAngle
this.endAngle = endAngle
this.color = color
this.x = 0
this.y = 0
this.text = "标签文字"
this.data = 1000
this.textAlign = 'left'
this.p1 = {
x: 0,
y: 0,
d: 20
};
this.p2 = {
x: 0,
y: 0,
d: 70
};
this.p3 = {
x: 0,
y: 0,
d: 20
};
this.p4 = {
x: 0,
y: 0,
d: 10
};
}
draw(ctx) {
const {
x,
y,
radius,
startAngle,
endAngle,
color
} = this
ctx.save()
ctx.beginPath()
ctx.fillStyle = color
ctx.moveTo(x,y) //这段非常重要,意思是把光标移动到圆心,这样绘制才是圆弧
ctx.arc(x, y, radius, startAngle, endAngle)
ctx.fill()
ctx.restore()
}
}
const item = new Sector()
item.x = 200
item.y = 200
item.draw(ctx)
</script>
</html>
网友评论