簡體   English   中英

如何使畫布背景透明

[英]How to make the canvas background transparent

我是使用html5 canvas的新手。

而且我想使用畫布生成煙霧動畫並將其放置在香煙圖像上方。

以下代碼是煙霧生成器的示例代碼,但我不知道如何使畫布的背景透明。

我嘗試了不同的globalCompositeOperation,但是似乎我走錯了方向。(我對畫布不太了解

我需要協助。

對不起,我的英語不好。

以下是我的代碼。

鏈接是我使用的示例代碼。

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");
});

畫布默認為透明。

但是無論如何,這個問題可以有一個非常簡單的解決方案,即不使用globalAlpha,也不使用rgba()顏色。 簡單有效的答案是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM