标签:width type pat setw line 水平 selector canvas offset
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>08-Canvas绘制表格</title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 canvas{ 12 display: block; 13 margin: 0 auto; 14 background: red; 15 } 16 </style> 17 </head> 18 <body> 19 <canvas width="500" height="400"></canvas> 20 <script> 21 // 1.拿到canvas 22 let oCanvas = document.querySelector("canvas"); 23 // 2.从canvas中拿到绘图工具 24 let oCtx = oCanvas.getContext("2d"); 25 // 3.定义变量保存小方格的尺寸 26 let gridSize = 50; 27 // console.log(oCanvas.offsetWidth); 28 // console.log(oCanvas.offsetHeight); 29 // console.log(oCanvas.clientWidth) 30 // console.log(oCanvas.clientHeight); 31 // console.log(oCanvas.scrollHeight); 32 // console.log(oCtx.canvas.width); 33 // console.log(oCtx.canvas.height); 34 // 4.拿到canvas的宽高 35 let canvasWidth = oCtx.canvas.width; 36 let canvasHeight = oCtx.canvas.height; 37 // 5.计算在垂直方向和水平方向可以绘制多少条横线 38 let row = Math.floor(canvasHeight / gridSize); 39 let col = Math.floor(canvasWidth / gridSize); 40 // 6.绘制垂直方向的横线 41 for(let i = 0; i < row; i++){ 42 oCtx.beginPath(); 43 oCtx.moveTo(0, i * gridSize - 0.5); 44 oCtx.lineTo(canvasWidth, i * gridSize - 0.5); 45 oCtx.strokeStyle = "#ccc"; 46 oCtx.stroke(); 47 } 48 // 7.绘制水平方向的横线 49 for(let i = 0; i < col; i++){ 50 oCtx.beginPath(); 51 oCtx.moveTo(i * gridSize - 0.5, 0); 52 oCtx.lineTo(i * gridSize - 0.5, canvasHeight); 53 oCtx.strokeStyle = "#ccc"; 54 oCtx.stroke(); 55 } 56 </script> 57 </body> 58 </html>
标签:width type pat setw line 水平 selector canvas offset
原文地址:https://www.cnblogs.com/gsq1998/p/12166060.html