Intento hacer una aplicación de pintura en javascript. Necesito hacer una cuadrícula cuadrada y presionando el botón. Hice tal cuadrícula pero no está en el fondo. ¿Cómo debo pasar la cuadrícula hecha por js en el fondo?
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" width="1000" height="1000" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas> </body> </html>Una solución fácil es usar dos lienzos en capas uno encima del otro. De esta manera, puede dibujar la cuadrícula en la capa de fondo independientemente del lienzo en primer plano.
Aquí hay un ejemplo:
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>