简体   繁体   中英

Examples of the 3 ways to draw a circle on HTML5 canvas

I can somewhat piece together a way to draw a circle using the ctx.arcTo method, but I am having difficulty understanding how to apply the Bezier equations to generically drawing an ellipse or circle (an arbitrarily close approximation of one) using them.

Wondering what the implementation of these three methods would be for drawing an arc (a segment, or all of, an ellipse or circle) from point a to point b, either bulging out or bulging in.

 var canvas = document.querySelector('canvas') var ctx = canvas.getContext('2d') ctx.moveTo(0, 0) arcTo(ctx, 100, 100, 50, 50, 20, 20) cubicTo(ctx, 110, 110, 10, 10, 120, 120) quadTo(ctx, 210, 210, 10, 10, 220, 220) function arcTo(ctx, xi, yi, r1, r2, xf, yf, bulgeIn) { ctx.save() ctx.beginPath() ctx.moveTo(xi, yi) ctx.arc(xi, yi, xf, yf, r1) ctx.closePath() ctx.stroke() ctx.restore() } function cubicTo(ctx, xi, yi, r1, r2, xf, yf, bulgeIn, approximationLevel) { // ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) } function quadTo(ctx, xi, yi, r1, r2, xf, yf, bulgeIn, approximationLevel) { // ctx.quadraticCurveTo(cpx, cpy, x, y) } 
 <style> canvas { background: #eee; width: 200px; height: 200px; } </style> <canvas></canvas> 

I'm wondering how to do both ellipses and circles at any angle, with any length partial segment of the circumference. Basically just the generic formula for html5 canvas.

在此处输入图片说明

It's all based on the same principle: You can draw a circle or ellipse by taking their parametric formula (x²+y² = some constant, and x²/a + y²/b = some constant, respectively), and joining up valid points for those formulae. Somehow. You can simply pick points that are so close that there's nothing "to join" since subsequent points are literally "the next pixel" (which is what arcTo does), but you can also space them further apart, and then you can join things up using:

  • lines
  • quadratic bezier curves
  • cubic bezier curve
  • literally any kind of curve, since you know all the points it needs to pass through

The challenge is not in joining up the points, it's knowing how far apart the points can be before things start to look pretty shitty.

For instance, for quadratic Bezier curves, you need 8 or more curves for things to look decent . Fewer than that, and it starts to look bad. For cubic Bezier curves, 4 is usually enough . For other curve types it really depends on the maths, which either you, or someone else, will have to work out to determine how many points you're going to need for things to look right.

But really, use arcTo, or even circle() and ellipse() if the programming language you're using has those. Don't approximate if you can just directly draw what you needed to draw.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM