简体   繁体   中英

How to draw in canvas 2D this shape and fill it with color?

画布2D

This should be without this diagonal . I want to draw two arcs one with x2 smaller radius, join them and fill() . I know how to calculate the end and beginning of an arc, problem is arcs are always drawn clockwise, so to draw second arc within same ctx.beginPath() I have to use something like ctx.moveTo() but problem with moveTo is I get two different paths as proof closePath() cause this diagonal.

So I want to know how to draw arc in other direction than clockwise or how to use moveTo() but still beeing able to fill this shape . Filling now cause following issue: 在此输入图像描述 White diagonal visible.

Arcs are not always drawn clockwise. The sixth parameter to .arc is a boolean which when true will make the arc be drawn anti-clockwise.

However you will also need to reverse the start and end angles, otherwise the arc will attempt to go the long way around:

 var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.arc(20, 20, 40, 30 * Math.PI / 180, 80 * Math.PI / 180); ctx.arc(20, 20, 150, 80 * Math.PI / 180, 30 * Math.PI / 180, true); ctx.closePath(); ctx.lineWidth = 3; ctx.stroke(); ctx.fillStyle = '#e0e0ff'; ctx.fill(); 
 <canvas id="c" width="200" height="200" /> 

Why not use the lineWidth property to make the arc thicker. In this case you'll only need one call to arc :

 let canvas = document.getElementById("canvas"), context = canvas.getContext("2d"); context.beginPath(); context.arc(20, 20, 40, 0, Math.PI / 4); context.lineWidth = 15; context.stroke(); 
 <canvas id="canvas"></canvas> 

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