1

I am a newbie on using html5 canvas.

And I'd like to use canvas generate a smoke animation and place it on top of a cigarette image.

The follow code is a sample code of a smoke generator but i don't know how to make the background of the canvas transparent.

I have try different globalCompositeOperation but it seem that i go into a wrong direction.(I don't know much about canvas

I need some help.

Sorry for my poor English.

The following is my code.

And the link is the sample code i used.

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");
});
L.C. Echo Chan
  • 586
  • 12
  • 29
  • 1
    possible duplicate of [How do I make a transparent canvas in html5?](http://stackoverflow.com/questions/4815166/how-do-i-make-a-transparent-canvas-in-html5) – GoBusto Feb 25 '15 at 09:17
  • 1
    **see this link** http://stackoverflow.com/questions/4815166/how-do-i-make-a-transparent-canvas-in-html5 – kishan Feb 25 '15 at 09:17

1 Answers1

0

Canvas transparent by default.

But anyway this question could have a pretty easy solution, which not using globalAlpha, and not using a rgba() color. The simple, effective answer is:

context.clearRect(0,0,width,height);
Alex Filatov
  • 2,232
  • 3
  • 32
  • 39