如何用arc方法创建自定义圆?

时间:2015-11-01 12:45:10

标签: javascript html css html5 canvas

我想自定义arc()功能,以便能够创建自己的圆圈,但我无法将其绘制成扁平的圆圈。

enter image description here

我该怎么做?



var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();

<canvas id="myCanvas" width="200" height="150" style="border:1px solid #d3d3d3;"></canvas>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:5)

弧将始终是一个圆圈。使用scale将您的圆转换为椭圆:

编辑:使用保存和恢复来保持画布状态。这将使线宽保持不变。

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.lineWidth=5;
ctx.save();
ctx.beginPath();
ctx.scale(2,1);
ctx.arc(50, 75, 40, 0, 2*Math.PI);
ctx.restore();
ctx.stroke();
<canvas id="myCanvas" width="200" height="150" style="border:1px solid #d3d3d3;"></canvas>

答案 1 :(得分:2)

使其与现有功能保持一致,而不必处理变化线宽的复杂性。这个通过扫除一组点来绘制弧线。将步骤calc中的2更改为更高的数字以使代码更快地运行或将2减少为1以获得更慢但更好的质量。使它小于1是没有意义的

// set up code;
var canvas = document.getElementById("canV");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height
ctx.clearRect(0,0,cw,ch)
ctx.globaleAlpha = 1;


// function to draw a arc with two radius wr the width radius
// and hr the height radius; start end are the start and end angles
function arc2(x, y, wr, hr, start, end){
    var i, xx, yy, step;
    step = 2 / Math.max(wr,hr); // get number of steps around
    for(i = start; i <= end; i+= step){ // from start to end
        if(i > end -step / 2){  // ensure that there is no floating
            i = end;              // point error at end of sweep
        }
        xx = Math.cos(i) * wr + x;      // calculate point on circle
        yy = Math.sin(i) * hr + y;
        if(i === start){                // if first Point move to
            ctx.moveTo(xx,yy);
        }else{
            ctx.lineTo(xx,yy);
        }
    }// all done return;
}
// demo to draw circles till the cows come home
var circleDraw = function () {
    var x, y, rw, rh;
    // get some randoms numbers for circles
    x = Math.random() * (cw / 2) + cw / 4;
    y = Math.random() * (ch / 2) + ch / 4;
    rw = Math.random() * ch / 4 + 20;
    rh = Math.random() * ch / 4 + 20;
    ctx.strokeStyle = "hsl(" + Math.floor(Math.random() * 260) + ",100%,50%)";
        ctx.fillStyle = "hsl(" + Math.floor(Math.random() * 260) + ",100%,50%)";
        ctx.lineWidth = Math.random() * 10;
  
    ctx.beginPath();
  
    // draw the arc with new function
    arc2(x, y, rw, rh, 0, Math.PI * 2);
    
    ctx.closePath(); // close the path
  
   // fill and or stoke it
    if (Math.random() > 0.5) {
        ctx.fill();
    }
    if (Math.random() > 0.5) {
        ctx.stroke();
    }
    setTimeout(circleDraw, 200);
}
setTimeout(circleDraw, 200);
.canC {
    width:256px;
    height:256px;
}
<canvas class="canC" id="canV" width=256 height=256></canvas>