这是我制作的小部件的图片:
这是调用所有原始形状的主要函数:
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>
首先,为什么当我在所有情况下都使用相同的手动类型循环时,只有外部容器的顶部和底部看起来很糟糕?其次,如何修复锯齿?
编辑:我一直在使用讨论的技术进行微调,这就是我得到的
最佳答案
同意,曲线总是容易出现锯齿。
或许尝试缩放圆的 Y 轴?
示例代码和演示:
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>
关于javascript - 如何在 HTML Canvas 上绘制一个比这个更平滑的椭圆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389954/