我正在深入研究 HTML5 canvas,并在使用本地安装的 Chrome 版本时遇到了一些奇怪的事情。这是 Linux 上的 Chrome 29。
我正在查看以下内容(来自 HTML5 Canvas 的示例代码,第 2 版):
//draw a big box on the screen
context.fillStyle = "black";
context.fillRect(10, 10, 200, 200);
context.save();
context.beginPath();
context.rect(0, 0, 50, 50);
context.clip();
//red circle
context.beginPath();
context.strokeStyle = "red";
context.lineWidth=5;
context.arc(100, 100, 100, (Math.PI/180)*0, (Math.PI/180)*360, false);
context.stroke();
context.closePath();
context.restore();
//reclip to the entire canvas
context.beginPath();
context.rect(0, 0, 500, 500);
context.clip();
//draw a blue line that is not clipped
context.beginPath();
context.strokeStyle = "blue"; //need list of available colors
context.lineWidth=5;
context.arc(100, 100, 50, (Math.PI/180)*0, (Math.PI/180)*360, false);
context.stroke();
context.closePath();
并且应该得到:
而是看:
我的研究表明 Chrome canvas 处于不断变化的状态,并且 arcs 过去曾出现过问题。但是,它在适用于 Windows 的 Chrome 的关闭版本和另一个 linux 桌面上的 Chrome 27 上似乎没问题。
我查看了我的 Chrome://flags,没有发现任何明显影响这一点的东西。
如有任何指导,我们将不胜感激。
编辑:
我在 chrome://flags 中尝试了#enable-experimental-canvas-features 和#disable-accelerated-2d-canvas 的变体,但没有成功。
这是一个 fiddle :
另一个编辑:
此代码适用于我机器上的 Chromium 28.0.1500.71。我开始怀疑这是一个 Chrome 错误。
最佳答案
圆弧经常被误解为圆,但实际上并非如此。与真实的圆圈(或本身是封闭路径的矩形,子路径)相反,它们具有开放的端点,因此可以连接到其他路径。
因此,正确关闭弧很重要。你几乎就在那里,但在你关闭它之前抚摸路径,关闭没有任何效果。
尝试切换两条线,使它们看起来像这样:
context.closePath();
context.stroke();
当然,您尝试使用的版本中可能存在错误(Chrome 过去有很多弧线问题)。
更新
要提供可能的解决方法,您可以这样做:
A) 手动创建一个像这样的圆圈(我尽我所能对其进行了优化):
function circle(ctx, cx, cy, radius) {
var x, y, i = 2 * Math.PI, dlt = radius * 0.0005;
while(i > 0) {
x = cx + radius * Math.cos(i);
y = cy + radius * Math.sin(i);
i === 4 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
i -= dlt;
}
ctx.closePath();
}
B) create a circle using a Bezier (这不会是一个完美的圆圈,但非常相似):
function drawEllipse(ctx, x, y, w, h) {
var kappa = 0.5522848,
ox = (w * 0.5) * kappa, // control point offset horizontal
oy = (h * 0.5) * kappa, // control point offset vertical
xe = x + w, // x-end
ye = y + h, // y-end
xm = x + w * 0.5, // x-middle
ym = y + h * 0.5; // y-middle
ctx.beginPath();
ctx.moveTo(x, ym);
ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
ctx.closePath();
ctx.stroke();
}
关于javascript - Chrome 的 HTML5 canvas 绘图问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18773357/