top of page

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

Build along to create a highlighted text with code

TUTORIAL

Build along to create a highlighted text with code

Build along to create an image-blend scroll effect

TUTORIAL

Build along to create an image-blend scroll effect

How to monitor your code for performance and error handling in Wix Studio

TUTORIAL

How to monitor your code for performance and error handling in Wix Studio

What do you think about the tutorial?

More creation-fueling resources

Find the answers you’re looking for.

Join the conversation, get updates and community support. 

Join us on Discord to connect and grow with fellow creators.

Collab with other web design and dev pros.

Get in touch with the Studio team. We're here to help.

New skills, new boundaries to break. 

Start creating

bottom of page