Build along to create a drawing effect on a section
Learn how to recreate this interactive effect where you can use your mouse to draw on a section.
Build along to create an interactive drawing effect with a custom element and code on Wix Studio.
Use this code to recreate the effect:
class DrawingCanvas extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.render();
this.initializeCanvas();
}
render() {
this.shadowRoot.innerHTML = `
<canvas id="drawingCanvas"></canvas>
`;
}
initializeCanvas() {
const pixelSize = 4;
const color = '#39D0B9';
const canvas = this.shadowRoot.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = color;
ctx.lineWidth = pixelSize;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
let isDrawing = false;
let lastX = 0;
let lastY = 0;
document.querySelector("body").addEventListener('mousemove', (event) => {
// Get the canvas's bounding rectangle
const canvasRect = canvas.getBoundingClientRect();
// Calculate mouse position relative to the canvas
const x = event.clientX - canvasRect.left;
const y = event.clientY - canvasRect.top;
if (!isDrawing) {
isDrawing = true;
[lastX, lastY] = [x, y];
return;
}
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
[lastX, lastY] = [x, y];
});
document.addEventListener('mouseleave', () => {
isDrawing = false;
[lastX, lastY] = [0, 0];
});
window.addEventListener('resize', () => {
const tempCanvas = document.createElement('canvas');
const tempCtx = tempCanvas.getContext('2d');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
tempCtx.drawImage(canvas, 0, 0);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = color;
ctx.lineWidth = pixelSize;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.drawImage(tempCanvas, 0, 0);
});
}
}
customElements.define('drawing-canvas', DrawingCanvas);
EXPLORE MORE CONTENT
More creation-fueling resources