Kyle Krzeski
Kyle Krzeski

Reputation: 6527

Fade out effect for line in HTML5 canvas with background image

I'm currently working on an HTML canvas example that fades out a line after it is drawn on a canvas, though my question is: how do I attain this while using a background image?

Live Demo (current code in a link at the bottom of this post)

CSS:

canvas {
  background-image: url("https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2018/02/PluralsightandSO.jpg");
  background-size: 100% 100%;
}

JavaScript:

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    painting = false,
    lastX = 0,
    lastY = 0;

canvas.width = canvas.height = 600;

canvas.onmousedown = function (e) {
    if (!painting) {
        painting = true;
    } else {
        painting = false;
    }

    lastX = e.pageX - this.offsetLeft;
    lastY = e.pageY - this.offsetTop;
};

canvas.onmousemove = function (e) {
    if (painting) {
        mouseX = e.pageX - this.offsetLeft;
        mouseY = e.pageY - this.offsetTop;

        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(mouseX, mouseY);
        ctx.stroke();

        lastX = mouseX;
        lastY = mouseY;
    }
}

function fadeOut() {
    ctx.fillStyle = "rgba(255,255,255,0.3)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    setTimeout(fadeOut,100);
}

fadeOut();

I realize fillRect is filling the entire canvas with the fillStyle so I assumed I could add the image to the canvas instead, but as you can tell, the animation is not the same by using this code instead:

var image = new Image();
image.src = "https://zgab33vy595fw5zq-zippykid.netdna-ssl.com/wp-content/uploads/2018/02/PluralsightandSO.jpg"
ctx.drawImage(image, 0, 0);

Current Live Demo (after changes described above) - it's too rigid and doesn't have as long of a tail

Any thoughts?

Upvotes: 1

Views: 879

Answers (2)

Kokodoko
Kokodoko

Reputation: 28128

You're drawing a 30% transparent square to get the 'fading' effect:

ctx.fillStyle = "rgba(255,255,255,0.3)";

So you need to draw the PNG transparently as well

canvas.onmousemove = function (e) {
    if (painting) {
        // set line alpha to 1
        ctx.globalAlpha = 1.0;
        // your paint code here
    }
}

function fadeOut() {
    var image = new Image();
    // set image alpha to 0.3
    ctx.globalAlpha = 0.3;
    // your draw image code here
}

By the way, you don't need to create the new image every time!

Example

Upvotes: 1

tomasantunes
tomasantunes

Reputation: 945

You need to specify width and height:

ctx.drawImage(image, 0, 0, 600, 600);

Upvotes: 0

Related Questions