Alpha in Canvas

when adding an image

by bjelline

HTML

<canvas id="canvas" width="400" height="400"></canvas>

CSS

#canvas {
      background-color:black;
  }

JavaScript

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

function Sprite() {
    // save this (refers to the sprite) to a variable
    // that can be used later in the onload callback function
    var that = this; 
    
    // load an image
    this.image = new Image();
    this.image.src = 'http://www.w3.org/2008/site/images/logo-w3c-screen-lg';

    // define random position
    this.posX = Math.random() * 200;
    this.posY = Math.random() * 200;
    // define random alpha value
    this.alpha = Math.random() * 0.8 + 0.2;

    // after image is loaded: display it in the canvas
    this.image.onload = function () {
        context.globalAlpha = that.alpha;
        context.drawImage(this, that.posX, that.posY);
    }


}

new Sprite();
new Sprite();
new Sprite();