Painting in Canvas which fades with time | Strange alpha layering behaviour

前端 未结 4 2116
旧时难觅i
旧时难觅i 2020-12-18 05:58

I\'m painting to a canvas which isn\'t being cleared and making it so that the canvas either fades to a solid colour over time, or fades in alpha revealing the layer behind.

4条回答
  •  温柔的废话
    2020-12-18 06:39

    Answering my own question with what I ended up going with - thanks to the responses, after learning that the core problem is a rounding issue I figured adding some random noise to the fade amount could help make sure it's not always rounding to the same number, kinda like giving it a shake when it's stuck.

    Here's that same jsfiddle modified: http://jsfiddle.net/R4V97/97/

    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.strokeStyle = "rgba(255,255,255,1)";
            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(mouseX, mouseY);
            ctx.stroke();
    
            lastX = mouseX;
            lastY = mouseY;
        }
    }
    
    function fadeOut() {
        var r = 0.3 + (Math.random()*0.1);
        ctx.fillStyle = "rgba(60,30,50,"+r+")";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        setTimeout(fadeOut,100);
    }
    
    fadeOut();
    

    This slightly compromises the smoothness of the fade, but it's a lot less noticeable/intrusive than the ghost trails.

提交回复
热议问题