See the Pen Canvas stripes by haiqing wang (@whqet) onCodePen.
效果如所示,顏色隨機。
canvas製作多彩條紋,html非常簡單。
<canvas id="canvas" class="opacity04" width="550" height="310">Your browser does not support the HTML5 Canvas element.</canvas>
CSS也非常簡單,主要實現彩條背景的100%顯示和修飾邊框。
html, body { background-color: #272727; padding: 0px; margin: 0px; overflow: hidden;}canvas { border: rgba(0,0,0,.1) solid 2px;}.opacity04{ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)"; /* ie8 */ filter:alpha(opacity=40); /* ie5-7 */ opacity: 0.4; /* css standard, currently it works in most modern browsers */}
JS部分是重點,代碼如下
$(function() { //變數初始化,獲得畫布及其寬和高 var canvas = document.getElementById('canvas'); var c = canvas.getContext('2d'); var width = canvas.width = window.innerWidth; var height = canvas.height = window.innerHeight; //設定條紋寬度 var lineWidth=10; //繪製黑色背景,最後效果中看不到,可以省略 c.fillStyle = "rgba(0, 0, 0, 1.0)"; c.fillRect(0, 0, width, height); //利用迴圈繪製彩條 for (var i=0; i<width; i=i+lineWidth) { c.beginPath(); c.lineWidth = lineWidth; c.strokeStyle = '#'+Math.floor(Math.random()*16777215).toString(16); c.moveTo(i, 0); c.lineTo(i, height); c.stroke(); }});
這樣可以繪製出邊緣清晰的條紋,本例接著使用模糊濾鏡美化效果,模糊濾鏡採用高人quasimondo的效果。在html中,添加js引用。
<script type="text/javascript" src="http://www.quasimondo.com/BoxBlurForCanvas/FastBlur.js"></script>
在JS中再添加模糊濾鏡的調用,實現canvas 的模糊效果。
$(function() { //變數初始化,獲得畫布及其寬和高 var canvas = document.getElementById('canvas'); var c = canvas.getContext('2d'); var width = canvas.width = window.innerWidth; var height = canvas.height = window.innerHeight; //設定條紋寬度 var lineWidth=10; //繪製黑色背景,最後效果中看不到,可以省略 c.fillStyle = "rgba(0, 0, 0, 1.0)"; c.fillRect(0, 0, width, height); //利用迴圈繪製彩條 for (var i=0; i<width; i=i+lineWidth) { c.beginPath(); c.lineWidth = lineWidth; c.strokeStyle = '#'+Math.floor(Math.random()*16777215).toString(16); c.moveTo(i, 0); c.lineTo(i, height); c.stroke(); } //調用高人的canvas模糊濾鏡,調用方法如下 // tackBlurCanvasRGBA( targetCanvasID, top_x, top_y, width, height, radius ); //or: stackBlurCanvasRGB( targetCanvasID, top_x, top_y, width, height, radius ); boxBlurCanvasRGBA("canvas", 0, 0, width, height, 20, 1);});
大家可以到我的codepen線上修改、體驗,或是下載收藏本效果。
---------------------------------------------------------------
前端開發whqet,關注web前端開發技術,分享網頁相關資源。
---------------------------------------------------------------