12.4 HTML Canvas样式

可以调整图形填充、画笔色彩和粗细

修改形状和路径的填充颜色

通过设置2D渲染上下文的fillStyle属性,你就能够修改形状和路径的填充颜色。代码如下:

context.fillStyle = "rgb(255, 0, 0)"; 
    context.fillRect(40, 40, 100, 100); 

在这个例子中,我们赋值了一个“rgb(红、绿、蓝)”颜色值,但是你也可以使用任何有效的css颜色值,如十六进制码(例如,#FF0000)或单词“red”。在这个例子中,颜色值设置为红色(纯红色,没有绿色和蓝色)。

在设置fillStyle属性之后,你所绘制的所有图形都会采用这个颜色。如果你接受这个结果,它就不是问题.但是如果你只希望修改一个对象的颜色,那么你一定要注意。有一个方法可以解决这个问题,就是当你在Canvas上绘制对象时,将fillStyle属性设置回黑色(或其他颜色),例如:

context.fillStyle = "rgb(255, 0, 0)"; 
    context.fillRect(40, 40, 100, 100); // Red square 
    context.fillRect(180, 40, 100, 100); // Red square 
    context.fillStyle = "rgb(0, 0, 0)"; 
    context.fillRect(320, 40, 100, 100); // Black square 

结果如图1所示。

将填充颜色改回黑色

还可以在描边图形和路径上使用strokeStyle属性实现变色效果。例如,下面的代码与前一个例子相同,唯一区别是它使用笔画描边而不是填充:

context.strokeStyle = "rgb(255, 0, 0)"; 
    context.strokeRect(40, 40, 100, 100); // Red square 
    context.strokeRect(180, 40, 100, 100); // Red square 
    context.strokeStyle = "rgb(0, 0, 0)"; 
    context.strokeRect(320, 40, 100, 100); // Black square 

结果如图2所示。

图2 修改描边颜色

完全可以使用fillStyle和strokeStyle为图形设置不同的填充和描边颜色。

这其中并没有什么复杂的地方,所有代码都非常简单。修改线条的颜色也是非常简单的:

context.strokeStyle = "rgb(255, 0, 0)"; context.beginPath(); 
    context.moveTo(40, 180); 
    context.lineTo(420, 180); // Red line 
    context.closePath(); 
    context.stroke(); 
    context.strokeStyle = "rgb(0, 0, 0)"; 
    context.beginPath(); 
    context.moveTo(40, 220); 
    context.lineTo(420, 220); // Black line 
    context.closePath(); 
    context.stroke(); 

结果如图3所示。

修改线条的颜色

以上就是在Canvas中修改颜色的所有方法。

修改线宽

修改颜色很有意思,但是我们例子中的线条还有些细。Canvas有一个方法可以增加线宽,即2D渲染上下文的lineWidth属性。lineWidth属性的默认值为1.但是可以将它修改为任意值。例如,修改红线和黑线的宽度:

context.lineWidth = 5; // Make lines thick 
    context.strokeStyle = "rgb(255, 0, 0)"; 
    context.beginPath();
    context.moveTo(40, 180); 
    context.lineTo(420, 180); // Red line 
    context.closePath(); 
    context.stroke(); 
    context.lineWidth = 20; // Make lines even thicker 
    context.strokeStyle = "rgb(0, 0, 0)";
    context.beginPath(); 
    context.moveTo(40, 220); 
    context.lineTo(420, 220); // Black line 
    context.closePath(); 
    context.stroke(); 

其结果是得到一条稍粗的红线和一条非常粗的黑线(见图4)。

修改线宽

lineWidth属性也会影响图形:

context.lineWidth = 5; // Make lines thick 
    context.strokeStyle = "rgb(255, 0, 0)"; 
    context.strokeRect(40, 40, 100, 100); // Red square 
    context.strokeRect(180, 40, 100, 100); // Red square 
    context.lineWidth = 20; // Make lines even thicker 
    context.strokeStyle = "rgb(0, 0, 0)"; 
    context.strokeRect(320, 40, 100, 100); // Black square

最终得到两个边框稍粗的红色正方形和一个边框非常粗的黑色正方形(见图5)。

图5 修改图形的线宽