HTML - Velocity Draw

Introduction to Velocity Draw

Hello, future web developers! Today, we're going to embark on an exciting journey into the world of HTML and a nifty little tool called Velocity Draw. As your friendly neighborhood computer teacher, I'm here to guide you through this adventure, step by step. Don't worry if you've never written a line of code before – we're starting from scratch!

HTML - Velocity Draw

What is Velocity Draw?

Velocity Draw is a simple yet powerful HTML5 canvas-based drawing application. It allows users to create drawings by moving their mouse or finger (on touch devices) across the screen. The cool part? The faster you move, the thinner the line becomes!

Setting Up Our HTML File

Let's start by creating a basic HTML structure for our Velocity Draw application. Open up your favorite text editor and type in the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Velocity Draw</title>
</head>
<body>
    <canvas id="drawingCanvas"></canvas>
    <script>
        // We'll put our JavaScript code here
    </script>
</body>
</html>

This sets up a basic HTML document with a canvas element where we'll do our drawing, and a script tag where we'll write our JavaScript code.

JavaScript Magic: Making the Canvas Interactive

Now, let's add some JavaScript to make our canvas interactive. We'll break it down into small, digestible chunks:

1. Setting up the canvas

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

Here, we're grabbing our canvas element, getting its 2D rendering context (which we'll use to draw), and setting its size to fill the entire window.

2. Tracking mouse movement

let isDrawing = false;
let lastX = 0;
let lastY = 0;
let velocity = 0;

canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);

We set up some variables to track whether we're drawing, the last position of the mouse, and the current velocity. Then we add event listeners for mouse actions.

3. Implementing drawing functions

function startDrawing(e) {
    isDrawing = true;
    [lastX, lastY] = [e.offsetX, e.offsetY];
}

function stopDrawing() {
    isDrawing = false;
}

function draw(e) {
    if (!isDrawing) return;

    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(e.offsetX, e.offsetY);

    const currentVelocity = Math.sqrt(
        Math.pow(e.offsetX - lastX, 2) + Math.pow(e.offsetY - lastY, 2)
    );
    velocity = 0.7 * velocity + 0.3 * currentVelocity;

    ctx.lineWidth = Math.max(1, 10 - velocity);
    ctx.stroke();

    [lastX, lastY] = [e.offsetX, e.offsetY];
}

These functions handle the actual drawing. The draw function is where the magic happens – it calculates the velocity based on how far the mouse has moved and adjusts the line width accordingly.

Putting It All Together

Now that we have all the pieces, let's combine them into our HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Velocity Draw</title>
    <style>
        body { margin: 0; overflow: hidden; }
        canvas { display: block; }
    </style>
</head>
<body>
    <canvas id="drawingCanvas"></canvas>
    <script>
        const canvas = document.getElementById('drawingCanvas');
        const ctx = canvas.getContext('2d');

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;
        let velocity = 0;

        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseout', stopDrawing);

        function startDrawing(e) {
            isDrawing = true;
            [lastX, lastY] = [e.offsetX, e.offsetY];
        }

        function stopDrawing() {
            isDrawing = false;
        }

        function draw(e) {
            if (!isDrawing) return;

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(e.offsetX, e.offsetY);

            const currentVelocity = Math.sqrt(
                Math.pow(e.offsetX - lastX, 2) + Math.pow(e.offsetY - lastY, 2)
            );
            velocity = 0.7 * velocity + 0.3 * currentVelocity;

            ctx.lineWidth = Math.max(1, 10 - velocity);
            ctx.stroke();

            [lastX, lastY] = [e.offsetX, e.offsetY];
        }
    </script>
</body>
</html>

How It Works

  1. When you press the mouse button, startDrawing is called, which sets isDrawing to true and records the starting position.
  2. As you move the mouse, draw is called repeatedly. It draws a line from the last position to the current position.
  3. The velocity is calculated based on how far the mouse has moved since the last call.
  4. The line width is set inversely proportional to the velocity – faster movement results in thinner lines.
  5. When you release the mouse button or move it out of the canvas, stopDrawing is called, which stops the drawing process.

Conclusion

Congratulations! You've just created your very own Velocity Draw application. Isn't it amazing how a few lines of code can create something so interactive and fun? As you play with your new drawing tool, think about how you might extend it. Could you add color options? What about different brush styles?

Remember, the key to becoming a great programmer is experimentation and practice. So don't stop here – keep exploring, keep coding, and most importantly, keep having fun!

Method Description
getElementById Retrieves an element from the DOM by its ID
getContext Gets the rendering context for the canvas
addEventListener Attaches an event handler to an element
beginPath Starts a new path in the canvas
moveTo Moves the drawing cursor to a specified point
lineTo Draws a line from the current point to a specified point
stroke Renders the defined path with the current stroke style
Math.sqrt Calculates the square root of a number
Math.pow Raises a number to a specified power
Math.max Returns the largest of zero or more numbers

Happy coding, future web wizards!

Credits: Image by storyset