效果图:
code:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Canvas</title> 9 <style> 10 canvas { 11 margin: 0 auto; 12 border: 1px solid #aaa; 13 display: block; 14 } 15 </style> 16 </head> 17 18 <body> 19 <canvas width="500px" height="500px" id="canvas"></canvas> 20 21 <script> 22 var canvas = document.querySelector("#canvas"); 23 var ctx = canvas.getContext("2d"); 24 25 function drawCoordinate() { 26 ctx.beginPath(); 27 ctx.moveTo(100, 100); 28 ctx.lineTo(100, 400); 29 ctx.lineTo(400, 400); 30 ctx.stroke(); 31 ctx.closePath(); 32 } 33 34 function drawChart() { 35 for (var i = 0; i < 5; i++) { 36 // [10, 290) 37 var height = Math.random() * 280 + 10; 38 ctx.fillStyle = "#" + parseInt(Math.random() * 0xffffff).toString(16); 39 ctx.fillRect(120 + i * 40, 400 - height, 20, height); 40 } 41 } 42 43 // step_01 画坐标图 44 drawCoordinate(); 45 // step_02 条形统计图 46 drawChart(); 47 </script> 48 </body> 49 50 </html>