[ html canvas createImageData 创建万花筒效果 ] canvas绘图属性 createImageData 属性讲解 及创建万花筒效果

 1 <!DOCTYPE html>
 2 <html lang='zh-cn'>
 3 <head>
 4 <title>Insert you title</title>
 5 <meta name='description' content='this is my page'>
 6 <meta name='keywords' content='keyword1,keyword2,keyword3'>
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 8 <link rel='stylesheet' type='text/css' href='./css/index.css' />
 9 <script type='text/javascript' src='./js/jquery-1.12.1.min.js'></script>
10 <style type='text/css'>
11 html,body,canvas {
12     margin: 0; padding: 0;
13 }
14 
15 html {
16     height: 100%;
17 }
18 
19 body {
20     background: #000;
21 }
22 
23 #can {
24     background: #FFF /* url('./images/index.jpg') no-repeat center; backgrond-size: cover */;
25     display: block; margin: 25px auto; border-radius: 2px; cursor: pointer;
26 }
27 </style>
28 <script type='text/javascript'>
29     $( function(){
30         var can = $( '#can' ).get( 0 );
31         var oCan = can.getContext( '2d' );
32         var oImg = new Image();
33         oImg.src = './images/index.jpg';
34         var gImg = oCan.getImageData( 50 , 30 , 100 , 150 );    /* 之所以进行获取,是为了循环中读取个数 */
35         oImg.onload = function(){
36             var num = 0;
37             var length = gImg.data.length;
38             var img = oCan.createImageData( 100 , 100 );
39             for( var i = 0 ; i < length ; i++ ){
40                 num = i % 4; /* 0 1 2 3 */
41                 switch( num ){
42                     case 0 :
43                         num = 0;
44                         img.data[ i ] = getRandomNum();
45                     break;
46                     case 1 :
47                         num = 255;
48                         img.data[ i ] = getRandomNum();
49                     break;
50                     case 2 :
51                         num = 0;
52                         img.data[ i ] = getRandomNum();
53                     break;
54                     case 3 :
55                         num = getRandomNum();
56                         img.data[ i ] = num;
57                     break;
58                 }
59             }
60             oCan.putImageData( img , 10 , 20 );
61         };
62         function getRandomNum(){
63             return Math.ceil( Math.random() * 255 ); /* 0-- 255 */
64         }
65         //alert(getRandomNum());
66     } );
67 </script>
68 </head>
69 <body>
70     <canvas id='can' width='300' height='168'>检测到您的浏览器版本过低请升级您的浏览器版本以获取更好的用户体验...</canvas>
71 </body>
72 </html>

 

posted @ 2016-10-11 16:20  窗棂  Views(663)  Comments(0Edit  收藏  举报