这一次讲解Canvas中的颜色应用,同时Canvas中的颜色还能带透明,太酷了~~
现在为止我们画的图形都是黑色的,这是Canvas绘制的默认色彩,要想换一种颜色的话,就得在实际画之前指定颜色。
- ctx.strokeStyle = color
—— 指定绘制线的颜色
- ctx.fillStyle = color
—— 指定填充的颜色
来看看实际的例子:
- onload = function() {
- draw();
- };
- function draw() {
- var canvas = document.getElementById('c1');
- if ( ! canvas || ! canvas.getContext ) { return false; }
- var ctx = canvas.getContext('2d');
- ctx.beginPath();
- ctx.fillStyle = 'rgb(192, 80, 77)'; // 红
- ctx.arc(70, 45, 35, 0, Math.PI*2, false);
- ctx.fill();
- ctx.beginPath();
- ctx.fillStyle = 'rgb(155, 187, 89)'; // 绿
- ctx.arc(45, 95, 35, 0, Math.PI*2, false);
- ctx.fill();
- ctx.beginPath();
- ctx.fillStyle = 'rgb(128, 100, 162)'; // 紫
- ctx.arc(95, 95, 35, 0, Math.PI*2, false);
- ctx.fill();
- }
效果如下图:
和普通的CSS中一样,我们指定颜色的时候还可以带一个alpha值(不过用的不多,IE9之前都不支持)。看代码:
- onload = function() {
- draw();
- };
- function draw() {
- var canvas = document.getElementById('c1');
- if ( ! canvas || ! canvas.getContext ) { return false; }
- var ctx = canvas.getContext('2d');
- ctx.beginPath();
- ctx.fillStyle = 'rgba(192, 80, 77, 0.7)'; //
- ctx.arc(70, 45, 35, 0, Math.PI*2, false);
- ctx.fill();
- ctx.beginPath();
- ctx.fillStyle = 'rgba(155, 187, 89, 0.7)'; //
- ctx.arc(45, 95, 35, 0, Math.PI*2, false);
- ctx.fill();
- ctx.beginPath();
- ctx.fillStyle = 'rgba(128, 100, 162, 0.7)'; //
- ctx.arc(95, 95, 35, 0, Math.PI*2, false);
- ctx.fill();
- }
结果就是下面这样:
和上面的代码基本没变化,就是把rgb(r, g, b)变成了rgba(r, g, b, a)而已,a的值也是0~1,0表示完全透明,1则是完全不透明(所以alpha的值实际上是“不透明度”)。
上面我们给每一个圆加了0.7的alpha值,不过我们每个圆的alpha都是一样的,每个都写一遍未免有些麻烦(说是我没觉得麻烦……只不过不这么说就没法引出这个新功能啊:)
- ctx.globalAlpha = alpha
这个参数指定了全局的alpha值,这么设定之后,所有画的图案都会有这么点的透明,除非你又特别指定了。所以把我们的第一个例子稍微改一下:
- onload = function() {
- draw();
- };
- function draw() {
- var canvas = document.getElementById('c1');
- if ( ! canvas || ! canvas.getContext ) { return false; }
- var ctx = canvas.getContext('2d');
- ctx.globalAlpha = 0.7; // 就多了这么一句
- ctx.beginPath();
- ctx.fillStyle = 'rgb(192, 80, 77)';
- ctx.arc(70, 45, 35, 0, Math.PI*2, false);
- ctx.fill();
- ctx.beginPath();
- ctx.fillStyle = 'rgb(155, 187, 89)';
- ctx.arc(45, 95, 35, 0, Math.PI*2, false);
- ctx.fill();
- ctx.beginPath();
- ctx.fillStyle = 'rgb(128, 100, 162)';
- ctx.arc(95, 95, 35, 0, Math.PI*2, false);
- ctx.fill();
- }
然后我们的结果就和2完全一样了:
画图多的时候,还是能少打很多字的。