很久没研究前端的东西,现在体验下Canvas的魅力。
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <title>Html5 之 Canvas</title> 5 <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> 6 <style type="text/css"> 7 body 8 { 9 font-size:inherit; 10 } 11 #demo_container 12 { 13 14 } 15 #demo_container h2 16 { 17 font-size:75%; 18 } 19 #no_pic 20 { 21 border:1px solid #ccc; 22 background-color:#f0f0f0; 23 } 24 </style> 25 <script type="text/javascript"> 26 function createDiagonal() 27 { 28 var canvas=document.getElementById("no_pic"); 29 var context=canvas.getContext("2d"); 30 context.beginPath(); 31 context.moveTo(0,0); 32 context.lineTo(150,150); 33 context.moveTo(0,150); 34 context.lineTo(150,0); 35 context.strokeStyle="#CCC"; 36 context.stroke(); 37 } 38 </script> 39 </head> 40 <body> 41 <div id="demo_container"> 42 <h2>无图片:</h2> 43 <canvas id="no_pic" width="150" height="150">您的浏览器不支持HTML5 Canvas.</canvas> 44 </div> 45 <script type="text/javascript"> 46 try 47 { 48 document.createElement("canvas").getContext("2d"); 49 createDiagonal(); 50 } 51 catch(e) 52 { 53 alert("您的浏览器不支持HTML5 Canvas."); 54 } 55 </script> 56 </body> 57 </html>
截图:
用的Editor是Sublime Text 2,推荐的前端工具:
canvas 2d api规范文档:
http://wenku.baidu.com/view/d841013d0912a2161479292d.html
网格:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <title>Html5 之 Canvas</title> 5 <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> 6 <style type="text/css"> 7 html,body 8 { 9 margin:0; 10 padding:0; 11 } 12 #no_pic 13 { 14 background-color:#FCFCFC; 15 } 16 </style> 17 <script type="text/javascript"> 18 function createGrids(rows,cols) 19 { 20 var canvas=document.getElementById("no_pic"); 21 var context=canvas.getContext("2d"); 22 23 context.strokeStyle="#333"; 24 for(var r=0;r<cols;r=r+10) 25 { 26 context.beginPath(); 27 if(r%50==0) 28 context.lineWidth=0.4; 29 else 30 context.lineWidth=0.2; 31 context.moveTo(0,r); 32 context.lineTo(rows,r); 33 context.stroke(); 34 } 35 context.lineWidth=1; 36 for(var c=0;c<rows;c=c+10) 37 { 38 context.beginPath(); 39 if(c%50==0) 40 context.lineWidth=0.4; 41 else 42 context.lineWidth=0.2; 43 context.moveTo(c,0); 44 context.lineTo(c,cols); 45 context.stroke(); 46 } 47 } 48 </script> 49 </head> 50 <body> 51 <canvas id="no_pic">您的浏览器不支持HTML5 Canvas.</canvas> 52 <script type="text/javascript"> 53 try 54 { 55 document.createElement("canvas").getContext("2d"); 56 var canvas=document.getElementById("no_pic"); 57 canvas.width = window.innerWidth; 58 canvas.height = window.innerHeight; 59 createGrids(canvas.width,canvas.height); 60 } 61 catch(e) 62 { 63 alert("您的浏览器不支持HTML5 Canvas."); 64 } 65 </script> 66 </body> 67 </html>
图