天天看點

HTML5顔色加透明度,詳解HTML5 Canvas繪制時指定顔色與透明度的方法

指定顔色

黑色是canvas繪制的預設色彩,要想換一種顔色的話,就得在實際畫之前指定顔色。

javascript code複制内容到剪貼闆

ctx.strokestyle = color

指定繪制線的顔色:

javascript code複制内容到剪貼闆

ctx.fillstyle = color

指定填充的顔色:

來看看實際的例子:

javascript

javascript code複制内容到剪貼闆

onload =function() {

draw();

};

functiondraw() {

varcanvas = document.getelementbyid('c1');

if( ! canvas || ! canvas.getcontext ) {returnfalse; }

varctx = 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();

}

效果如下圖:

HTML5顔色加透明度,詳解HTML5 Canvas繪制時指定顔色與透明度的方法

指定透明度

和普通的css中一樣,我們指定顔色的時候還可以帶一個alpha值(不過用的不多,ie9之前都不支援)。看代碼:

javascript

javascript code複制内容到剪貼闆

onload =function() {

draw();

};

functiondraw() {

varcanvas = document.getelementbyid('c1');

if( ! canvas || ! canvas.getcontext ) {returnfalse; }

varctx = 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();

}

結果就是下面這樣:

HTML5顔色加透明度,詳解HTML5 Canvas繪制時指定顔色與透明度的方法

和上面的代碼基本沒變化,就是把rgb(r, g, b)變成了rgba(r, g, b, a)而已,a的值也是0~1,0表示完全透明,1則是完全不透明(是以alpha的值實際上是“不透明度”)。

全局透明globalalpha這個也是很簡單的一個屬性,預設值為1.0,代表完全不透明,取值範圍是0.0(完全透明)~1.0。這個屬性與陰影設定是一樣的,如果不想針對全局設定不透明度,就得在下次繪制前重置globalalpha。

總結一下:基于狀态的屬性有哪些?

——globalalpha

——globalcompositeopeartion

——strokestyle

——textalign,textbaseline

——linecap,linejoin,linewidth,miterlimit

——fillstyle

——font

——shadowblur,shadowcolor,shadowoffsetx,shadowoffsety

我們通過一個代碼,來體驗一下globalalpha的神奇之處~

javascript code複制内容到剪貼闆

html>

全局透明

body { background: url("./images/bg3.jpg") repeat; }

#canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; }

你的浏覽器居然不支援canvas?!趕快換一個吧!!

window.onload =function(){

varcanvas = document.getelementbyid("canvas");

canvas.width = 800;

canvas.height = 600;

varcontext = canvas.getcontext("2d");

context.fillstyle ="#fff";

context.fillrect(0,0,800,600);

context.globalalpha = 0.5;

for(vari=0; i<=50; i++){

varr = math.floor(math.random() * 255);

varg = math.floor(math.random() * 255);

varb = math.floor(math.random() * 255);

context.fillstyle ="rgb("+ r +","+ g +","+ b +")";

context.beginpath();

context.arc(math.random() * canvas.width, math.random() * canvas.height, math.random() * 100, 0, math.pi * 2);

context.fill();

}

};

運作結果:

HTML5顔色加透明度,詳解HTML5 Canvas繪制時指定顔色與透明度的方法

是不是非常的酷?終于有點藝術家的範兒了吧。