canvas繪製背景參照表格

Html

  <canvas id="canvas"></canvas>

JavaScript

let canvas = document.querySelector('#canvas')
let width = 1024;
let height = 768;
canvas.setAttribute('width',width)
canvas.setAttribute('height', height)

let ctx = canvas.getContext("2d");

ctx.translate(0, 0);
ctx.lineWidth = 1;
ctx.save();

let i = 0.5;
let g = 0; 
// 繪製橫線
while (i <= height) {
   ctx.restore();
   if (g % 4 == 0) 
     ctx.strokeStyle = "rgb(229,229,229)"
   else 
     ctx.strokeStyle = "rgb(242,242,242)"
   ctx.beginPath();
   ctx.moveTo(0, i);
   ctx.lineTo(width, i);
   i += grid;
   g++;
   ctx.stroke()
}
i = 0.5;
g = 0;
// 繪製縱線
while (i <= width) {
  ctx.restore();
  if (g % 4 == 0) 
    ctx.strokeStyle = "rgb(229,229,229)"
  else 
    ctx.strokeStyle = "rgb(242,242,242)"
  ctx.beginPath();
  ctx.moveTo(i, 0);
  ctx.lineTo(i,height );
  i += grid;
  g++;
  ctx.stroke()
}

效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章