javascript - How can I draw a circle on a canvas? -


i'm using javascript , canvas draw mathematically designed scale (for measuring torque, includes newton-meters , foot-pounds). had been positioning ticks using trigonometry, , drawing arcing lines using arc, naturally. problem came when needed line up, there strange distortion. drew large circle , compared circular selection in gimp , there distortion. circles consistent every 45 degrees around circles, between nodes canvas drawn circle deviates outwards, octagon can been rounded far outwards approximate circle.

why these distortions occur? how can draw circular circle on canvas?

this code used generate distorted circle.

<!doctype html> <html>   <body>     <canvas width=8000 height=8000 id='mycanvas'></canvas>     <script>       var canvas = document.getelementbyid('mycanvas');       var context = canvas.getcontext('2d');       context.beginpath();       context.arc(4000, 4000, 3200, 0, math.pi*2, false);       context.linewidth = 1;       context.strokestyle = '#ff0000';       context.linecap = 'square';       context.stroke();     </script>   </body> </html> 

this may not minimal, know not of relevance of context.linecap, it's vestige of code based on. following screenshot shows difference between circle drawn gimp , circle drawn chrome screenshot

this chromium bug #164241 (declared fixed, although fix may not have made out yet). short answer is: chrome approximating circles composite bezier curves.

i unable replicate myself on chromium (43.0.2357.130, ubuntu) occur on firefox 39, although couldn't find similar bug report firefox. fact it's correct every 90 degrees (not 45, @ least not me) indicates circles being approximated 4 curves, curve endpoints guaranteed correct.

luckily there's simple workaround: create path consisting of more 4 curves. 8 or 6 should sufficient radii you're using can use more if want play safe. or increase number of curves function of radius, although calculating optimal function (the minimum n produce accurate circle given radius r) non-trivial.

context.beginpath(); var n=8; // 4 default behaviour. higher better, slower (var i=0; i<n; i++) {     context.arc(4000, 4000, 3200, math.pi*2*i/n, math.pi*2*(i+1)/n, false); } context.stroke(); 

see this question.

(and yes, linecap red herring.)


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -