如何在HTML Canvas上绘制一个比这个更平滑的椭圆?

时间:2015-09-04 04:14:03

标签: javascript html5-canvas smooth

这是我制作的小部件的图片:

enter image description here

这是调用所有原始形状的主函数:

function cylinder(ctx, w, h, fill_percent){
    y_origin = h;
    x_origin = 0;
    drawContainerBottom(ctx, x_origin, y_origin, w, h);
    drawContentBottom(ctx, x_origin, y_origin, w, h);
    drawContentFront(ctx, x_origin, y_origin, w, h, fill_percent);
    drawContentTop(ctx, x_origin, y_origin, w, h, fill_percent);
    drawContainerFront(ctx, x_origin, y_origin, w, h);
    drawContainerTop(ctx, x_origin, y_origin, w, h);
}

这是绘制外部容器顶部的函数,主要看起来很糟糕:

function drawContentTop(ctx, x, y, w, h, fill_percent){
    Contents_offset=5;
    w=w-2*Contents_offset;
    x=x+Contents_offset;
    h=h;
    y=y-h+Contents_offset+(h-w/4-2*Contents_offset)*(1-fill_percent);
    var i; 
    var xPos; 
    var yPos; 
    var twoPi = 2 * Math.PI;
    ctx.beginPath();

    //Top
    for (i = 0; i < twoPi; i += 0.001) {
        xPos = (x + w / 2) - (w / 2 * Math.cos(i));
        yPos = (y + w / 8) + (w / 8 * Math.sin(i));

        if (i === 0) {
            ctx.moveTo(xPos, yPos);
        } else {
            ctx.lineTo(xPos, yPos);
        }
    }

    ctx.fillStyle="rgba(0, 99, 188, .5)";
    ctx.fill();
    ctx.strokeStyle="rgba(0, 99, 188, 1)";
    ctx.stroke();
};

以下是我的称呼方式:

<canvas name='pool_graphic' class='pool_graphic' width='125' height='125' style='padding:10px'></canvas><br />
<canvas name='pool_graphic' class='pool_graphic' width='125' height='125' style='padding:10px'></canvas><br />
<script>
    $("td canvas[name='pool_graphic']").each(function(){
        var ctx = this.getContext('2d');
        var padding = this.style.padding.replace(/[^0-9]+/, '');
        var w=this.width
        var h=this.height;
        var fill_percent=1;
        cylinder(ctx, w, h, fill_percent);

    });
</script>

首先,为什么在所有情况下使用相同的手动类型循环时,只有外部容器的顶部和底部看起来很糟糕?其次,我该如何修复锯齿状?

编辑:只是使用所讨论的技术保持tweeking,这就是我得到的

enter image description here

1 个答案:

答案 0 :(得分:1)

同意,曲线总是容易出现锯齿。

也许尝试缩放圆圈的Y?

enter image description here

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.fillRect(0,0,cw,ch);

oval(150,150,75,.38);

function oval(cx,cy,radius,percentY){
  // draw thrice with slight offset to fill a few jaggies
  drawOval(cx,cy,radius,percentY);
  drawOval(cx,cy+0.50,radius,percentY);
  drawOval(cx+0.50,cy+0.75,radius,percentY);
}

function drawOval(cx,cy,radius,percentY){
  ctx.beginPath();
  ctx.translate(cx,cy);
  ctx.scale(1,percentY);
  ctx.arc(0,0,radius,0,Math.PI*2);
  ctx.lineWidth=1;
  ctx.strokeStyle='gainsboro';
  ctx.stroke();
  ctx.stroke();
  ctx.setTransform(1,0,0,1,0,0);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>