Answer the question
In order to leave comments, you need to log in
How to change brush size when resizing canvas?
Initial project (raw):
mixed-pickle.surge.sh
Main js:
import drawCanvas from './main/canvas/drawCanvas';
window.onload = () => {
drawCanvas(16, 16);
};
import drawOnTheCanvas from './drawOnTheCanvas';
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
let cells = [];
export default function drawCanvas(cellWidth, cellHeight) {
cells = [];
for (let top = 0; top < canvasWidth; top += cellWidth) {
for (let left = 0; left < canvasHeight; left += cellHeight) {
const cell = {
top,
left,
fill(color) {
context.fillStyle = color;
context.fillRect(this.top, this.left, cellWidth, cellHeight);
},
drawBorder() {
context.beginPath();
context.strokeStyle = 'rgba(168, 168, 168, 1)';
context.moveTo(this.top - 0.5, this.left - 0.5);
context.lineTo(this.top - 0.5, this.left + cellWidth - 0.5);
context.lineTo(this.top + cellHeight - 0.5, this.left + cellWidth - 0.5);
context.lineTo(this.top + cellHeight - 0.5, this.left - 0.5);
context.lineTo(this.top - 0.5, this.left - 0.5);
context.stroke();
},
getTop() {
return this.top;
},
getLeft() {
return this.left;
},
};
cells.push(cell);
cell.fill('rgba(112, 112, 112, 1)');
cell.drawBorder();
}
}
drawOnTheCanvas(cellWidth, cellHeight, cells);
}
const canvas = document.getElementById('canvas');
const canvasWidth = canvas.width;
export default function drawOnTheCanvas(cellWidth, cellHeight, cells) {
const cellsInRow = Math.floor(canvasWidth / cellWidth);
function getCellByPosition(top, left) {
const topIndex = Math.floor(top / cellHeight) * cellsInRow;
const leftIndex = Math.floor(left / cellWidth);
window.console.log(cells[topIndex + leftIndex]);
return cells[topIndex + leftIndex];
}
function fillCellAtPositionIfNeeded(x, y) {
const cellUnderCursor = getCellByPosition(x, y);
cellUnderCursor.fill('#fff');
}
function handleMouseMove(event) {
fillCellAtPositionIfNeeded(event.layerX, event.layerY);
event.stopImmediatePropagation();
}
function handleMouseDown(event) {
fillCellAtPositionIfNeeded(event.layerX, event.layerY);
canvas.addEventListener('mousemove', handleMouseMove, false);
event.stopImmediatePropagation();
}
function handleMouseUp() {
canvas.removeEventListener('mousemove', handleMouseMove);
}
canvas.addEventListener('mousedown', handleMouseDown, false);
canvas.addEventListener('mouseup', handleMouseUp, false);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question