Drawing App with JavaScript, HTML, and CSS

Creating a drawing app is a fun and interactive way to learn web development. This tutorial will walk you through the steps to build a basic drawing application using JavaScript, HTML5, and CSS. By the end of this guide, you'll have a fully functional drawing app where users can draw on a canvas, change brush sizes, select colors, and clear the canvas.

Project Setup

Create a Project Directory: Name it drawing-app. This will organize your project files.

File Structure:
  • index.html: Contains the HTML markup for the application.
  • style.css: Styles the application.
  • script.js: Contains the logic of the Drawing application.

Development Steps

1. HTML Markup (index.html)

The foundation of our drawing app is a simple HTML structure, which includes an <canvas> element where the drawing will take place and a toolbox for the controls, such as size adjustment, color picker, and a clear button.

Let's open the index.html file and add the following code to it:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Drawing App</title>
  </head>
  <body>
    <canvas id="canvas" width="800" height="700"></canvas>
    <div class="toolbox">
      <button id="decrease">-</button>
      <span id="size">10</span>
      <button id="increase">+</button>
      <input type="color" id="color">
      <button id="clear">X</button>
    </div>

    <script src="script.js"></script>
  </body>
</html>

2. style.css - CSS Styling 

The CSS styling gives our app a clean and user-friendly interface. The Roboto font's modern look and consistent color scheme make the toolbox intuitive to use. Each button and the color picker are given equal importance in the layout to facilitate easy access.

Let's open the style.css file and add the following CSS code to it:  
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');

* {
  box-sizing: border-box;
}

body {
  background-color: #f5f5f5;
  font-family: 'Roboto', sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

canvas {
  border: 2px solid steelblue;
}

.toolbox {
  background-color: steelblue;
  border: 1px solid slateblue;
  display: flex;
  width: 804px;
  padding: 1rem;
}

.toolbox > * {
  background-color: #fff;
  border: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  height: 50px;
  width: 50px;
  margin: 0.25rem;
  padding: 0.25rem;
  cursor: pointer;
}

.toolbox > *:last-child {
  margin-left: auto;
}

3. script.js - JavaScript Functionality 

The core functionality of our drawing app is handled by JavaScript. It includes event listeners for mouse actions on the canvas and functions to draw on the canvas.

Let's open the script.js file and add the following JavaScript code to it:    
const canvas = document.getElementById('canvas');
const increaseBtn = document.getElementById('increase');
const decreaseBtn = document.getElementById('decrease');
const sizeEL = document.getElementById('size');
const colorEl = document.getElementById('color');
const clearEl = document.getElementById('clear');

const ctx = canvas.getContext('2d');

let size = 10
let isPressed = false
colorEl.value = 'black'
let color = colorEl.value
let x
let y

canvas.addEventListener('mousedown', (e) => {
    isPressed = true

    x = e.offsetX
    y = e.offsetY
})

document.addEventListener('mouseup', (e) => {
    isPressed = false

    x = undefined
    y = undefined
})

canvas.addEventListener('mousemove', (e) => {
    if(isPressed) {
        const x2 = e.offsetX
        const y2 = e.offsetY

        drawCircle(x2, y2)
        drawLine(x, y, x2, y2)

        x = x2
        y = y2
    }
})

function drawCircle(x, y) {
    ctx.beginPath();
    ctx.arc(x, y, size, 0, Math.PI * 2)
    ctx.fillStyle = color
    ctx.fill()
}

function drawLine(x1, y1, x2, y2) {
    ctx.beginPath()
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2)
    ctx.strokeStyle = color
    ctx.lineWidth = size * 2
    ctx.stroke()
}

function updateSizeOnScreen() {
    sizeEL.innerText = size
}

increaseBtn.addEventListener('click', () => {
    size += 5

    if(size > 50) {
        size = 50
    }

    updateSizeOnScreen()
})

decreaseBtn.addEventListener('click', () => {
    size -= 5

    if(size < 5) {
        size = 5
    }

    updateSizeOnScreen()
})

colorEl.addEventListener('change', (e) => color = e.target.value)

clearEl.addEventListener('click', () => ctx.clearRect(0,0, canvas.width, canvas.height))

Here’s a breakdown of the JavaScript functionality: 

Canvas Setup and Event Listeners: We start by setting up the canvas context and defining event listeners for mouse down, up, and move actions. These events track whether the user is drawing and the position of the cursor on the canvas.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

Drawing Functions: The drawCircle and drawLine functions are where the magic happens. They use the canvas API to draw on the canvas based on the user's input.

function drawCircle(x, y) {
  ctx.beginPath();
  ctx.arc(x, y, size, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
}

function drawLine(x1, y1, x2, y2) {
  ctx.beginPath();
  ctx.moveTo(x1, y1);
  ctx.lineTo(x2, y2);
  ctx.strokeStyle = color;
  ctx.lineWidth = size * 2;
  ctx.stroke();
}

Toolbox Functionality: The increase and decrease buttons adjust the brush size, the color input changes the brush color, and the clear button wipes the canvas clean.

increaseBtn.addEventListener('click', () => {
  size += 5;
  updateSizeOnScreen();
});

decreaseBtn.addEventListener('click', () => {
  size -= 5;
  updateSizeOnScreen();
});

colorEl.addEventListener('change', (e) => color = e.target.value);

clearEl.addEventListener('click', () => ctx.clearRect(0,0, canvas.width, canvas.height));

Open index.html in Browser 

 Let's open the index.html file in the browser, and you will be able to see the following screen: 
Drawing App with JavaScript, HTML, and CSS

Conclusion

Building a drawing app is a fantastic project for web developers looking to explore the capabilities of the HTML5 element, CSS, and JavaScript. This app not only provides a fun way to create digital artwork but also offers a hands-on experience with event handling and the canvas API. Whether you're a beginner or an experienced developer, this project can help you sharpen your skills in creating interactive web applications. Feel free to expand upon this project by adding features like saving drawings, implementing undo and redo functionality, or even sharing drawings online. Happy coding!

Comments