1

I am trying to fade an image in a canvas environment. Essientially what I want to do is while moving an image from left to right, I want to fade it from 0% alpha to 100% alpha. When I comment the globalAlpha and alpha info out in my code, it moves like I want it to, my only issue is getting it to fade. I am able to get the globalAlpha function to work, but it affects all the artwork in the canvas area. Is there a way I can just affect the one element? eventually I will want to fade in multiple elements at different times in the animation based on a timer, but if I can get this to work first I can go from there.

window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() 
{
    canvasApp();
}
function canvasSupport () 
{
    return Modernizr.canvas;
}
function canvasApp()
    {
        if (!canvasSupport()) 
        {
            return;
        }



        var pointImage = new Image();
        pointImage.src = "images/barry.png";
        var barry = new Image();
        barry.src = "images/barry.png";
        /*var alpha = 0;
        context.globalAlpha = 1;*/

        function drawScreen() 
        {

            //context.globalAlpha = 1;
            context.fillStyle = '#EEEEEE';
            context.fillRect(0, 0, theCanvas.width, theCanvas.height);
            //context.globalAlpha = alpha;

            //Box
            context.strokeStyle = '#000000';
            context.strokeRect(1, 1, theCanvas.width-2, theCanvas.height-2);


            if (moves > 0 ) 
            {
                moves--;
                ball.x += xunits;
                ball.y += yunits;
            }



            context.drawImage(barry, ball.x, ball.y);

            /*context.restore();
            alpha += .1;
            if (alpha > 1)
            {
                alpha = 0;
            }*/


        }

        var speed = 1;
        var p1 = {x:20,y:250};
        var p2 = {x:40,y:250};
        var dx = p2.x - p1.x;
        var dy = p2.y - p1.y;
        var distance = Math.sqrt(dx*dx + dy*dy);
        var moves = distance/speed;
        var xunits = (p2.x - p1.x)/moves;
        var yunits = (p2.y - p1.y)/moves;
        var ball = {x:p1.x, y:p1.y};
        var points = new Array();
        theCanvas = document.getElementById("canvas");
        context = theCanvas.getContext("2d");
        ctx = theCanvas.getContext("2d");
        setInterval(drawScreen, 10);
    }

any suggestions are welcome!

user1075004
  • 131
  • 1
  • 3
  • 9

1 Answers1

0

I think this other question will give you a way to do so.

it shows how to load an element in the canvas context then how to fade it in..

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

Community
  • 1
  • 1