gpt4 book ai didi

javascript - 如何阻止 HTML5 Canvas 重影?

转载 作者:行者123 更新时间:2023-12-02 15:59:52 26 4
gpt4 key购买 nike

我做了一个小程序:

  1. 将 Canvas 内的鼠标光标更改为黑色方 block
  2. 给黑色方 block 留下一条漂亮的轨迹,随着时间的推移逐渐消失(程序的要点)

代码如下:

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(),但它只是清除整个动画,不留下任何内容可显示。最好的情况是,它只是删除了轨迹,并且仅单独淡化了方形光标,但当淡化过程完成时,它仍然无法使光标完全透明。我尝试过查找有关它的帖子,但没有找到任何给出明确答案的内容,而且最重要的是,没有找到包含有效示例的帖子。

有什么想法吗?

最佳答案

尝试列出位置列表,这不会留下鬼迹!

我的代码:

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/

编辑:使光标保持不变。

关于javascript - 如何阻止 HTML5 Canvas 重影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com