html5 canvas 像素随机百分之十显示
<!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>