如何停止HTML5 Canvas Ghosting?

时间:2015-07-08 13:54:35

标签: javascript html5 canvas

我制作了一个小程序:

  1. 将画布内的鼠标光标更改为黑色方块
  2. 为黑色方块提供了一条随着时间的推移逐渐消失的好路径(程序的重点)
  3. 以下是代码:

    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    
    canvas.style.cursor = 'none'; // remove regular cursor inside canvas
    
    function getMousePos(canvas, e) {
      var rect = canvas.getBoundingClientRect();
      return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
      };
    }
    
    function fadeCanvas() {
      ctx.save();
      ctx.globalAlpha = 0.1; // the opacity (i.e. fade) being applied to the canvas on each function re-run
      ctx.fillStyle = "#FFF";
      ctx.fillRect(0, 0, canvas.width, canvas.height); // area being faded (whole canvas)
      ctx.restore();
      requestAnimationFrame(fadeCanvas); // animate at 60 fps
    }
    fadeCanvas();
    
    function draw(e) {
      var pos = getMousePos(canvas, e);
      ctx.fillStyle = "black";
      ctx.fillRect(pos.x, pos.y, 8, 8); // the new cursor
    }
    addEventListener('mousemove', draw, false); 
    

    以下是一个实例:https://jsfiddle.net/L6j71crw/2/

    问题

    然而,小径并没有完全消失,并留下了一个重影痕迹。

    问:如何删除鬼影痕迹?

    我尝试过以不同的方式使用clearRect(),但它只是清除整个动画而不显示任何内容。它最多只是删除了跟踪,只是单独淡化方形光标,但是当淡入淡出过程完成时它仍然没有使光标完全透明。我试过找到关于它的帖子,但我发现没有什么能给出明确的答案 - 最重要的是 - 没有一个有实际例子的帖子。

    有什么想法吗?

1 个答案:

答案 0 :(得分:2)

尝试列出一个位置列表,这不会留下幽灵痕迹!

我的代码:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var Positions = [];
var maxlength = 20;

canvas.style.cursor = 'none'; // remove regular cursor inside canvas

var V2 = function(x, y){this.x = x; this.y = y;};

function getMousePos(canvas, e) {
    // ctx.clearRect(0, 0, canvas.width, canvas.height);
    var rect = canvas.getBoundingClientRect();
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}

function fadeCanvas() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for(var e = 0; e != Positions.length; e++)
    {
        ctx.fillStyle = ctx.fillStyle = "rgba(0, 0, 0, " + 1 / e + ")";
        ctx.fillRect(Positions[e].x, Positions[e].y, 8, 8);

    }
    if(Positions.length > 1)
        Positions.pop()

    //ctx.save();
    //ctx.globalAlpha = 0.5; // the opacity (i.e. fade) being applied to the canvas on each function re-run
    //ctx.fillStyle = "#fff";
    //ctx.fillRect(0, 0, canvas.width, canvas.height); // area being faded (whole canvas)
    //ctx.restore();
    requestAnimationFrame(fadeCanvas); // animate at 60 fps
}
fadeCanvas();

function draw(e) {
    var pos = getMousePos(canvas, e);
    Positions.unshift(new V2(pos.x, pos.y));
    if(Positions.length > maxlength)
        Positions.pop()
    //ctx.fillStyle = "black";
    //ctx.fillRect(pos.x, pos.y, 8, 8); // the new cursor
}
addEventListener('mousemove', draw, false); 

JSFiddle:https://jsfiddle.net/L6j71crw/9/

编辑:使游标保持不变。