veteri
veteri

Reputation: 113

Javascript: Canvas Drawing (2 identical files with different results)

So, I'm going through my javascript book right now and there was a little example of canvas drawing. I copied the code out of the book but the canvas stays white.

I then went on to download the author's collection of all the scripts shown in the book and with his code, it surprisingly works.

To me both codes look identical, the only thing that differs is that I use " " for strings while the author used ' '.

This is my code:

function init() {
    let canvas = document.getElementById("canvas");
    canvas.addEventListener("mousemove", handleMouseMove, false);
    let context = canvas.getContext("2d");
    let started = false;

    function handleMouseMove(e) {
        let x, y;
        if (e.clientX || e.clientX == 0) {
            x = e.clientX;
            y = e.ClientY;
        }
        if (!started) {
            context.beginPath();
            context.moveTo(x, y);
            started = true;
        } else {
            context.lineTo(x, y);
            context.stroke();
        }
    }

}

document.addEventListener("DOMContentLoaded", init);

And this is the code of the author:

function init() {
    let canvas = document.getElementById('canvas');
    canvas.addEventListener('mousemove', handleMouseMove, false);
    let context = canvas.getContext('2d');
    let started = false;
    function handleMouseMove(e) {
        let x, y;
        if (e.clientX
            || e.clientX == 0) {
            x = e.clientX;
            y = e.clientY;
        }
        if (!started) {
            context.beginPath();
            context.moveTo(x, y);
            started = true;
        } else {
            context.lineTo(x, y);
            context.stroke();
        }
    }

}

document.addEventListener('DOMContentLoaded', init);

Upvotes: 2

Views: 72

Answers (1)

driconmax
driconmax

Reputation: 942

You have a little problem in the handleMouseMove function. You write

y = e.ClientY;

But e.ClientY doesn't exist, it should be:

y = e.clientY;

Upvotes: 2

Related Questions