gpt4 book ai didi

javascript - 当我为图像或 smth 设置动画时如何避免背景颜色不透明问题?

转载 作者:行者123 更新时间:2023-11-29 17:52:21 27 4
gpt4 key购买 nike

此屏幕截图和代码片段将向您展示我的麻烦。如何避免这种情况?可能是我以错误的方式这样做吗?如果可能的话,我想看一些代码示例。

enter image description here

let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");

canvas.width = 500;
canvas.height = 500;

let image = new Image();

image.src= "https://www.html5rocks.com/static/images/identity/HTML5_Badge_256.png";

function rand(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}

image.addEventListener("load", function()
{

let top = canvas.width / 2 - image.width / 2;
let left = canvas.height / 2 - image.height / 2;

function render()
{

top += rand(-2, 2);
left += rand(-2, 2);


ctx.save();
ctx.globalAlpha = 0.05;
ctx.fillStyle = "#9ea7b8";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ctx.drawImage(image, top, left, image.width, image.height);
requestAnimationFrame(render);
}

render();
});
<canvas></canvas>

最佳答案

好的,经过多次尝试,工作完成了。每一帧我都绘制完整路径。

let canvas = document.querySelector("canvas");
let ctx = canvas.getContext("2d");
let tail = 20;

canvas.width = 800;
canvas.height = 600;

let image = new Image();

let opacity = [];

image.src= "https://www.html5rocks.com/static/images/identity/HTML5_Badge_256.png";

for(let i = 1; i <= tail; i++)
{
opacity.push(i / tail);
}


function rand(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}

image.addEventListener("load", function()
{

let frames = [];

frames.push({
x: canvas.width / 2 - image.width / 2,
y: canvas.height / 2 - image.height / 2
});

for (let i = 1; i < tail; i++)
{
frames.push({
x: frames[i - 1].x + rand(-2, 2),
y: frames[i - 1].y + rand(-2, 2)
});
}

function render()
{

frames.shift();
frames.push({
x: frames[frames.length - 1].x + rand(-2, 2),
y: frames[frames.length - 1].y + rand(-2, 2)
});

ctx.globalAlpha = 1;
ctx.fillStyle = "#9ea7b8";
ctx.fillRect(0, 0, canvas.width, canvas.height);

for(let i = 0; i < tail; i++)
{
ctx.save();
ctx.drawImage(image, frames[i].x, frames[i].y, image.width, image.height);
ctx.globalAlpha = opacity[tail - 1 - i];
ctx.fillRect(frames[i].x - tail, frames[i].y - tail, image.width + tail + tail, image.height + tail + tail);
ctx.restore();
}

requestAnimationFrame(render);
}

render();
});
<canvas></canvas>

关于javascript - 当我为图像或 smth 设置动画时如何避免背景颜色不透明问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332043/

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