我注意到很多时候,每当我尝试在HTML5画布上一次绘制许多对象时,颜色并不总是以我想要的方式出现,事物只是无法呈现,等等。
我应该如何一次绘制许多不同的东西?我应该自己绘制基本形状,然后绘制文本,然后绘制线条等吗?
谢谢
答案 0 :(得分:0)
最简单的是,您需要确保致电:
ctx.beginPath()
(如果您打算绘制的每个新形状,如果它们是不同的颜色)。
或者如果要绘制的路径都是相同的颜色,则仅调用一次ctx.stroke()
。
例如,假设画两条黑色的线:
ctx.beginPath()
// Draw one line:
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.stroke(); // Stroke that line
// Draw another line:
ctx.moveTo(x2, y2);
ctx.lineTo(x3, y3);
// This does not only stroke the second line
// Since you never called beginPath() again, it strokes
// Both the first and second line as two sub-paths of the same path
ctx.stroke(); // Strokes both line
第二次致电stroke()
时,您将重新开始第一行。当然,如果您更改颜色,这将是一个大问题,但是即使您不更改颜色,将第一行抚摸两次也会使其稍粗一些。
“最佳实践”解决方案是最有效的绘制方法,即绘制一次相同颜色的所有路径,只需调用一次beginPath
,致电stroke
:
ctx.beginPath()
// Draw one line:
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
// Do not stroke
// Draw another line:
ctx.moveTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.stroke(); // Strokes both lines with the same color
如果计划绘制不同的颜色,则不能执行此操作。您必须通过每次调用beginPath
并每次调用stroke
来创建新路径:
// Draw one line:
ctx.beginPath();
ctx.moveTo(x0, y0);
ctx.lineTo(x1, y1);
ctx.strokeStyle = 'red';
ctx.stroke();
// Draw another line:
ctx.beginPath();
ctx.moveTo(x2, y2);
ctx.lineTo(x3, y3);
ctx.strokeStyle = 'blue';
ctx.stroke();