canvas多彩条纹背景

See the Pen Canvas stripes by haiqing wang (@whqet) onCodePen.

效果如下图所示,颜色随机。

canvas多彩条纹背景

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前端开发技术,分享网页相关资源。
---------------------------------------------------------------

canvas多彩条纹背景

上一篇:PXE无人值守安装系统


下一篇:hdu 2546