<canvas></canvas>
body {
margin: 0;
overflow: hidden;
}
canvas {
image-rendering: pixelated;
}
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const shapes = [];
let currentShape = null;
const update = (time) => {
context.clearRect(0, 0, canvas.width, canvas.height);
context.globalAlpha = 0.4;
if (shapes.length === 0 && currentShape === null) {
const fontSize = Math.max(12, Math.min(18 * (canvas.width / canvas.height), 24));
context.font = `${fontSize}px Segoe UI`;
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText('Зажмите ЛКМ; проведите мышью; отпустите ЛКМ', canvas.width / 2, canvas.height / 2);
} else {
shapes.forEach(shape => context.fill(shape));
if (currentShape !== null) {
context.stroke(currentShape);
}
}
requestAnimationFrame(update);
};
const resize = () => {
[canvas.width, canvas.height] = [innerWidth, innerHeight];
};
const init = () => {
canvas.addEventListener('mousedown', event => {
currentShape = new Path2D();
currentShape.moveTo(event.offsetX, event.offsetY);
});
canvas.addEventListener('mouseup', event => {
if (currentShape !== null) {
shapes.push(currentShape);
currentShape = null;
}
});
canvas.addEventListener('mousemove', event => {
if (currentShape !== null) {
currentShape.lineTo(event.offsetX, event.offsetY);
}
});
resize();
requestAnimationFrame(update);
};
window.addEventListener('load', init);
window.addEventListener('resize', resize);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.