Skip to content

Instantly share code, notes, and snippets.

@thinkgarden
Created September 15, 2018 15:22
Show Gist options
  • Save thinkgarden/0de69697ea47590ef5a6b79dc454cd05 to your computer and use it in GitHub Desktop.
Save thinkgarden/0de69697ea47590ef5a6b79dc454cd05 to your computer and use it in GitHub Desktop.
[canvas]

绘制基本图形

arc()方法
arc(x, y, radius, startRad, endRad, [anticlockwise]);

** 绘制圆和圆弧 **

getRads(degrees) {
   return (Math.PI * degrees) / 180;
},

ctx.arc(x, y, r,  0, 2pi, false);

** 绘制扇形 **

使用arc()除了可以绘制弧线和圆之外,还可以绘制扇形。绘制扇形关键点是通过moveTo()把起始点位置设置为圆心处,然后通过closePath()闭合路径。

ctx.lineWidth = 1; 
ctx.strokeStyle = '#e3f'; 
ctx.fillStyle = '#e3f'; 
ctx.beginPath(); 
// 起始点设置在圆心处 
ctx.moveTo(arc.x, arc.y); 
ctx.arc(arc.x, arc.y, arc.r,getRads(-45),getRads(45)); 
// 闭合路径 
ctx.closePath(); 
ctx.stroke()
arcTo()方法
arcTo(x1, y1, x2, y2, radius)

绘制圆角矩形

绘制圆角矩形

drawRoundRect(x,y,width,height,radius,fill,stroke){
  ctx.save(); 
  ctx.beginPath(); 
  // draw top and top right corner 
  ctx.moveTo(x + r, y); 
  ctx.arcTo(x + width, y, x + width, y + r, r); 
  // draw right side and bottom right corner 
  ctx.arcTo(x + width, y + height, x + width - r, y + height, r); 
  // draw bottom and bottom left corner 
  ctx.arcTo(x, y + height, x, y + height - r, r); 
  // draw left and top left corner 
  ctx.arcTo(x, y, x + r, y, r); 
  if (fill) { ctx.fill(); } 
  if (stroke) { ctx.stroke(); } 
  ctx.restore();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment