指定顏色
黑色是Canvas繪制的默認色彩,要想換一種顏色的話,就得在實際畫之前指定顏色。
JavaScript Code復制內容到剪貼板
ctx.strokeStyle = color
指定繪制線的顏色:
JavaScript Code復制內容到剪貼板
ctx.fillStyle = color
指定填充的顏色:
來看看實際的例子:
JavaScript
JavaScript Code復制內容到剪貼板
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之前都不支持)。看代碼:
JavaScript
JavaScript Code復制內容到剪貼板
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的值實際上是“不透明度”)。
全局透明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復制內容到剪貼板
!DOCTYPE html html lang= zh head meta charset= UTF-8 title 全局透明 /title style body { background: url( ./images/bg3.jpg ) repeat; } #canvas { border: 1px solid #aaaaaa; display: block; margin: 50px auto; } /style /head body p id= canvas-warp canvas id= canvas 你的瀏覽器居然不支持Canvas?!趕快換一個吧!! /canvas script window.onload = function(){ var canvas = document.getElementById( canvas canvas.width = 800; canvas.height = 600; var context = canvas.getContext( 2d context.fillStyle = #FFF context.fillRect(0,0,800,600); context.globalAlpha = 0.5; for(var i=0; i i++){ var R = Math.floor(Math.random() * 255); var G = Math.floor(Math.random() * 255); var B = 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(); /script /body /html
運行結果:
是不是非常的酷?終于有點藝術家的范兒了吧。
相關推薦:
使用HTML5 Canvas為圖片填充顏色和紋理
以上就是HTML5 Canvas繪制時指定顏色與透明度的方法的詳細內容,其它編程語言
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答