Drawing an ellipse in a Canvas is a common requirement. The ellipse method is added to the new HTML Canvas 2D Context W3C draft, but this method has not been implemented by most browsers currently, so we need to use the arc or arcTo method combined with scale deformation to draw an ellipse. Sample Code: [html] <canvas width = "400" height = "300"> </canvas> <script> var ctx = document. querySelector ('canvas '). getContext ('2d '); ctx. lineWidth = "10"; ctx. scale (1, 0.2); ctx. arc( 150,150,100, 0, Math. PI * 2, false); ctx. stroke (); </script> <canvas width = "400" height = "300"> </canvas> <script> var ctx = document. querySelector ('canvas '). getContext ('2d '); ctx. lineWidth = "10"; ctx. scale (1, 0.2); ctx. arc( 150,150,100, 0, Math. PI * 2, false); ctx. stroke (); </script>
A little wrong, because the line width is uneven, stroke is also affected by scale. It requires a little skill to correct this problem. Sample Code: [html] <canvas width = "400" height = "300"> </canvas> <script> var ctx = document. querySelector ('canvas '). getContext ('2d '); ctx. lineWidth = "10"; ctx. save (); ctx. scale (1, 0.2); ctx. arc( 150,150,100, 0, Math. PI * 2, false); ctx. restore (); ctx. stroke (); </script> <canvas width = "400" height = "300"> </canvas> <script> var ctx = document. querySelector ('canvas '). getContext ('2d '); ctx. lineWidth = "10"; ctx. save (); ctx. scale (1, 0.2); ctx. arc( 150,150,100, 0, Math. PI * 2, false); ctx. restore (); ctx. stroke (); </script>
Now it's even and perfect. Tip: save the canvas state first, then zoom in and out, call the path command, restore the canvas state, and draw the stroke. The key point is to save and zoom, restore first and then stroke.