Main Logo
homelink tutorialslink softwarelink comicslink aboutlink contactlink

Tutorial: How to Create Gradients Using HTML5


Example JavaScript
    <script language="javascript" type="text/javascript">
        window.onload = DrawGradient;

        function DrawGradient() 
        {
            //Initialize variables
            var myCanvas = document.getElementById("GradientCanvas");      //get canvas by its ID
            var myContext = myCanvas.getContext("2d");                     //Get 2 Dimensional Context of Canvas
            var myGradient = myContext.createLinearGradient(0, 0, 0, 500); //begin at (0, 0) and end at (0, 500)

            //define gradient (use numbers between 0 and 1 to define where colors stop)
            myGradient.addColorStop(0, "#4BC8EA");
            myGradient.addColorStop(0.2, "White");

            //draw gradient
            myContext.fillStyle = myGradient;
            myContext.fillRect(0, 0, 500, 100);

            //add some text
            myContext.font = "bold 40px Sans-Serif";
            myContext.fillStyle = "Black";
            myContext.textAlign = "center";
            myContext.textBaseline = "bottom";
            myContext.fillText("J|McConahie.com", 250, 75);
        } 
    </script>
    
Example Markup
    <canvas id="GradientCanvas" width="500" height="100">
    </canvas>
    
View Example