码迷,mamicode.com
首页 > Web开发 > 详细

html5 canvas 像素随机百分之十显示

时间:2015-02-16 22:05:57      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script>
window.onload = function ()
{
    var oc = document.getElementById(‘c1‘);
    var ogc = oc.getContext(‘2d‘);
    var ali = document.getElementsByTagName(‘li‘);
    
    for(var i = 0; i < ali.length; i++)
    {
        ali[i].onclick = function ()
        {
            var str = this.innerHTML;
            var h = 180;
            
            ogc.clearRect(0,0,oc.width,oc.height);
            ogc.font = h + ‘px impact‘;
            ogc.fillStyle = ‘red‘;
            ogc.textBaseline = ‘top‘;
            var w = ogc.measureText(str).width;
            ogc.fillText(str,(oc.width - w)/2,(oc.height - h)/2);
            var oimg = ogc.getImageData((oc.width - w)/2,(oc.height - h)/2,w,h);
            ogc.clearRect(0,0,oc.width,oc.height);
            
            var arr = randnum(w*h,w*h/10);    
            var newimg = ogc.createImageData(w,h)
            for(var i = 0; i <arr.length; i++)
            {
                newimg.data[arr[i]*4] = oimg.data[arr[i]*4];
                newimg.data[arr[i]*4 + 1] = oimg.data[arr[i]*4 + 1];
                newimg.data[arr[i]*4 + 2 ] = oimg.data[arr[i]*4 + 2];
                newimg.data[arr[i]*4 + 3] = oimg.data[arr[i]*4 + 3];
            }
            
            ogc.putImageData(newimg,(oc.width - w)/2,(oc.height - h)/2);        
        }
    }
    
    function randnum( iall,inow)
    {
        var arr = [];
        var newarr = [];
        
        for(var i = 0; i < iall; i++)
        {
            arr.push(i);
        }
        
        for(var i = 0; i< inow; i++)
        {
            newarr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
        }
        
        return newarr
    }
}
</script>
<style>
body{
    background:pink;
    }
#c1{
    background:white;
    }    
</style>
</head>

<body>
<canvas id="c1" width="400" height="400"></canvas>
<ul style="float:left;font-size:30px;">
    <li>新</li>
    <li>年</li>
    <li>快</li>
    <li>乐</li>
</ul>
</body>
</html>

 

html5 canvas 像素随机百分之十显示

标签:

原文地址:http://www.cnblogs.com/mayufo/p/4294523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!