gpt4 book ai didi

javascript - 如何使 Canvas 背景透明

转载 作者:行者123 更新时间:2023-11-28 07:34:58 26 4
gpt4 key购买 nike

我是使用 html5 canvas 的新手。

我想使用 Canvas 生成烟雾动画并将其放置在香烟图像的顶部。

以下代码是烟雾生成器的示例代码,但我不知道如何使 Canvas 的背景透明。

我尝试了不同的 globalCompositeOperation 但似乎我进入了错误的方向。(我对 Canvas 不太了解

我需要一些帮助。

抱歉我的英语不好。

以下是我的代码。

链接是我使用的示例代码。

http://codepen.io/CucuIonel/pen/hFJlr

function start_smoke( smoke_id ) {
var canvas = document.getElementById(smoke_id);
var w = canvas.width = 200,
h = canvas.height = 150;
var c = canvas.getContext('2d');

var img = new Image();
img.src = 'http://oi41.tinypic.com/4i2aso.jpg';
var position = {x: w / 2, y: h};
var particles = [];
var random = function (min, max) {
return Math.random() * (max - min) * min;
};

function Particle(x, y) {
this.x = x;
this.y = y;
this.velY = -2;
this.velX = (random(1, 10) - 5) / 10;
this.size = random(3, 5) / 10;
this.alpha = 0.3;
this.update = function () {
this.y += this.velY;
this.x += this.velX;
this.velY *= 0.99;
if (this.alpha < 0)
this.alpha = 0;
c.globalAlpha = this.alpha;
c.save();
c.translate(this.x, this.y);
c.scale(this.size, this.size);
c.drawImage(img, -img.width / 2, -img.height / 2);
c.restore();
this.alpha *= 0.96;
this.size += 0.02;//
};
}

var draw = function () {
var p = new Particle(position.x, position.y);
particles.push(p);
while (particles.length > 500) particles.shift();
c.globalAlpha = 1;
c.fillRect(0, 0, w, h);

for (var i = 0; i < particles.length; i++) {
particles[i].update();
}
};
setInterval(draw, 1000 / 20);
}


$(function(){
start_smoke("main_censer_smoke");
});

最佳答案

Canvas 默认透明。

但无论如何,这个问题可以有一个非常简单的解决方案,不使用 globalAlpha,也不使用 rgba() 颜色。简单有效的答案是:

context.clearRect(0,0,width,height);

关于javascript - 如何使 Canvas 背景透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715125/

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