在画布背景上设置js制作的网格

Posted

技术标签:

【中文标题】在画布背景上设置js制作的网格【英文标题】:set grid made by js on the background of canvas 【发布时间】:2022-01-19 17:08:48 【问题描述】:

我尝试用 javascript 制作绘画应用程序。我需要制作方形网格并按下按钮。我做了这样的网格,但它不在背景上。我应该如何在后台传递js制作的网格?

function print_grid() 

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillRect(0, 0, 5100, 5100);
    ctx.clearRect(0, 0, 5100, 5100);


    ctx.beginPath();
    for (let i = 0; i < 39; i++)
    
        
        ctx.lineWidth = 1;
        ctx.moveTo(50*i, 0);
        ctx.lineTo(50*i, 5100);
        ctx.moveTo(0, 50*i);
        ctx.lineTo(5100, 50*i);
    
    ctx.stroke();
<!DOCTYPE html>
<html>
<body>
    <h1>Board</h1>
    
    <button onclick="print_grid()">square</button>

    <p >draw!!!</p>
    
    <canvas id="myCanvas"   style="border:1px solid #d3d3d3;">
        Your browser does not support the HTML5 canvas tag.
    </canvas>

</body>
</html>

【问题讨论】:

【参考方案1】:

一个简单的解决方案是使用两个相互叠加的画布。这样您就可以将网格绘制到独立于前景中的画布的背景层上。

这是一个例子:

const canvas = document.getElementById('canvas2');
const ctx = canvas.getContext('2d');

let coordinates = 
  x: 0,
  y: 0
;

let painting = false;

function getPosition(event) 
  coordinates.x = event.clientX - canvas.offsetLeft;
  coordinates.y = event.clientY - canvas.offsetTop;


function startPainting(event) 
  painting = true;
  getPosition(event);


function stopPainting() 
  painting = false;


function draw(event) 
  if (!painting) return;
  ctx.beginPath();
  ctx.lineWidth = 5;
  ctx.lineCap = 'round';
  ctx.strokeStyle = 'red';
  ctx.moveTo(coordinates.x, coordinates.y);
  getPosition(event);
  ctx.lineTo(coordinates.x, coordinates.y);
  ctx.stroke();


function clearCanvas() 
  ctx.clearRect(0, 0, canvas.width, canvas.height);


function printGrid() 
  let backgroundCanvas = document.getElementById('canvas');
  let context = backgroundCanvas.getContext("2d");
  context.beginPath();
  for (let a = 0; a < 10; a++) 
    context.moveTo(0, parseInt(a * (backgroundCanvas.height / 9)));
    context.lineTo(backgroundCanvas.width, parseInt(a * (backgroundCanvas.height / 9)));
    context.moveTo(parseInt(a * (backgroundCanvas.width / 9)), 0);
    context.lineTo(parseInt(a * (backgroundCanvas.width / 9)), backgroundCanvas.height);
  
  context.stroke();
  context.closePath();


printGrid();

document.addEventListener('mousedown', startPainting);
document.addEventListener('mouseup', stopPainting);
document.addEventListener('mousemove', draw);
<button onclick='clearCanvas();'>Clear</button>
<div>
  <canvas id='canvas' style='position: absolute'></canvas>
  <canvas id='canvas2' style='position: absolute'></canvas>
</div>

【讨论】:

以上是关于在画布背景上设置js制作的网格的主要内容,如果未能解决你的问题,请参考以下文章

ad封装背景网格怎么调出来

从数据 url 设置 fabric.js 画布背景

如何在 html5 中制作透明画布?

如何用PS制作花型背景图

ps画布设置为透明后,画板依然显示白色,怎么恢复透明格子?

将图像数据URI(base64)设置为画布背景