HTML5 Canvas Slideshow

HTML5 Canvas Slideshow

40 552
HTML5 Canvas Slideshow
HTML5 Canvas Slideshow

HTML5 Canvas Slideshow

In this tutorial we are making a HTML5 Slideshow (canvas) with own animated transitioning effect. The main idea – drawing images with higher contrast in the ends of transitions.

Here are our demo and downloadable package:

Live Demo

Ok, download the source files and lets start coding !


Step 1. HTML

This is markup of our result slideshow page. Here it is.

index.html

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>HTML5 Canvas Slideshow | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script src="js/pixastic.custom.js"></script>
        <script src="js/script.js"></script>
    </head>
    <body>
        <header>
            <h2>HTML5 Canvas Slideshow</h2>
            <a href="http://www.script-tutorials.com/html5-canvas-slideshow/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </header>
        <div class="container">
            <div class="slides">
                <img src="images/pic1.jpg" />
                <img src="images/pic2.jpg" />
                <img src="images/pic3.jpg" />
                <img src="images/pic4.jpg" />
                <img src="images/pic5.jpg" />
                <img src="images/pic6.jpg" />
                <img src="images/pic7.jpg" />
            </div>
            <canvas id="slideshow" width="900" height="300"></canvas>
        </div>
    </body>
</html>

Step 2. CSS

Here are all stylesheets

css/main.css

/* page layout styles */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#eee;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
header {
    background-color:#212121;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    position:relative;
    width:100%;
    z-index:100;
}
header h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
header a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
header .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}
.container {
    color: #000;
    margin: 20px auto;
    position: relative;
    width: 900px;
}
#slideshow {
    border:1px #000 solid;
    box-shadow:4px 6px 6px #444444;
    display:block;
    margin:0 auto;
    height:300px;
    width:900px;
}
.container .slides {
    display:none;
}

Step 3. JS

js/pixastic.custom.js

Pixastic – JavaScript Image Processing Library. I have used it to change brightness and contrast of our canvas. You can download this library here. Or, you can find this library in our package too.

js/script.js

var canvas, ctx;
var aImages = [];
var iCurSlide = 0;
var iCnt = 0;
var iSmTimer = 0;
var iContr = 0;
var iEfIter = 50;

$(function(){
    // creating canvas objects
    canvas = document.getElementById('slideshow');
    ctx = canvas.getContext('2d');

    // collect all images
    $('.slides').children().each(function(i){
        var oImg = new Image();
        oImg.src = this.src;
        aImages.push(oImg);
    });

    // draw first image
    ctx.drawImage(aImages[iCurSlide], 0, 0);

    var iTimer = setInterval(changeSlideTimer, 5000); // set inner timer
});

function changeSlideTimer() {
    iCurSlide++;
    if (iCurSlide == $(aImages).length) {
        iCurSlide = 0;
    }

    clearInterval(iSmTimer);
    iSmTimer = setInterval(drawSwEffect, 40); // extra one timer
}

// draw switching effect
function drawSwEffect() {
    iCnt++;

    if (iCnt <= iEfIter / 2) {
        iContr += 0.004;

        // change brightness and contrast
        Pixastic.process(canvas, 'brightness',
            {
                'brightness': 2,
                'contrast': 0.0 + iContr,
                'leaveDOM': true
            },
            function(img) {
                ctx.drawImage(img, 0, 0);
            }
        );
    }

    if (iCnt > iEfIter / 2) {
        // change brightness
        Pixastic.process(canvas, 'brightness',
            {
                'brightness': -2,
                'contrast': 0,
                'leaveDOM': true
            },
            function(img) {
                ctx.drawImage(img, 0, 0);
            }
        );
    }

    if (iCnt == iEfIter / 2) { // switch actual image
        iContr = 0;
        ctx.drawImage(aImages[iCurSlide], 0, 0);

        Pixastic.process(canvas, 'brightness',
            {
                'brightness': iEfIter,
                'contrast': 0,
                'leaveDOM': true
            },
            function(img) {
                ctx.drawImage(img, 0, 0);
            }
        );
    } else if (iCnt == iEfIter) { // end of cycle, clear extra sub timer
        clearInterval(iSmTimer);
        iCnt = 0;
        iContr = 0;
    }
}

As you can see – main functionality is easy. I have defined main timer (which will change images), and one inner time, which will use to change brightness and contrast of our canvas.


Live Demo

Conclusion

Hope that today’s html5 slideshow lesson was interesting for you as always. We have made another one nice html5 example. I will be glad to see your thanks and comments. Good luck!

SIMILAR ARTICLES


40 COMMENTS

  1. Great tutorial. When we first load demo it takes few seconds for the first image to be displayed. Is there a way to correct it?

    • Hi sajid,
      Do you want to add thumb-based switcher of slides somewhere in the top? If so, Firstly, you have to prepare thumbnail images for it (as example 32×32 icons). Then you will need to put them into layout into a new (DIV). Something like that:
      <div class="nav">__thumbnail_images__</div>
      after – you have to prepare CSS styles for this panel. And only after – you can start making own custom JS code to switch images by click event by these thumbs.
      It can be significant changes for a single comment answer

  2. I downloaded the package, and when I went to open it up, it never got past the first image. I tried the live demo and worked without problem. Any thoughts?

      • HI,
        I have the same problem: it never got past the first image.
        I am running it on my local pc.
        Any thoughts?

        Thanks,

      • Hi Offir,
        Try to search for any possible errors on your version, it is possible that there is some JS error. You can use ‘Firebug’ plugin to locate this problem

  3. I am a beginner to HTML, CSS and JAVASCRIPT. I was able to understand the code easily. I am gonna use it in my future projects.

  4. Hi,
    I am an artist. I have coded my own website and put a lot of effort into SEO. (I retired from software engineering 10 years ago, so I am very rusty and it takes a while for me to get through code.) An HTML slide show was just what I needed, so I found the code, below and adjusted it to what I needed. Your code seems to be a lot more complex. It will take me a while to get through the code to understand it, but can you explain what the difference between your code and the code below is? I did notice that your slideshow has a nice fade in transition, where mine is just a straight replacement of images. It looks to me like the code in drawSwEffect() is handling this, and that may be why your code is so much longer. Is this true? Also, does your code need any special special http-equiv meta tag? The one I am using is: “meta http-equiv=”X-UA-Compatible” content=”IE=edge,chrome=1″”
    Thanks for listening,
    Velvet

    In the Head section:
    “var image1=new Image()”
    “image1.src=”/images/SlideImage1b.jpg”"
    “var image2=new Image()”
    “image2.src=”/images/SlideImage2b.jpg”"
    “var image3=new Image()”
    “image3.src=”/images/SlideImage3b.jpg”"
    “var image4=new Image()”
    “image4.src=”/images/SlideImage4b.jpg”"
    “var image5=new Image()”
    “image5.src=”/images/SlideImage5b.jpg”"
    “var image6=new Image()”
    “image6.src=”/images/SlideImage6b.jpg”"
    “var image7=new Image()”
    “image7.src=”/images/SlideImage7b.jpg”"

    In the Body section:
    “div id=”slideimg”"
    ” img src=”../images/SlideImage1.jpg” name=”slide” width=”873? height=”322?”
    ” alt=”The creation of art: Original fine art painting, decorative and tole painting, metalsmithing, collage, beading, polymer clay sculpture.” ”
    “/div”
    ” script”
    ” <!–"
    " //variable that will increment through the images"
    " var step=1"

    " function slideit()"
    " {"
    " //if browser does not support the image object, exit.""
    " if (!document.images)"
    " return"
    "document.images.slide.src=eval("image"+step+".src")"
    " if (step”
    ” /script”

    • Hello Velvet,
      This is great that you (in your age) is still active, especially in web development. Yes, the ‘drawSwEffect’ function is used to draw this transition effect. You asked me about if you need to use that meta tag, no, you don’t need to do it (this is for another purpose)

  5. Sorry about all the questions, but I have just one last one. You have quite a few .js files in “script src” lines. The only thing I have in the script line is type=”text/javascript”. Why are you calling in all of those .js files? Are they not included when I just have the text/javascript? Are the “Pixastic.process” and “ctx.drawImage” not usually included without specifically calling those files? How did you know which files you had to include? One last question: Why did you put a “$” in front of the first function?
    Thanks for your patience,
    Velvet

    • You have to include all JS files that you are going to use. As for – type=”text/javascript”, this is up to you, basically, it is not required and you can omit it.
      Regarding $ in the
      $(function(){
      all the inner code will be executed when the page is loaded (jQuery)

  6. hi there
    tanks for this tutorial
    that was so usefull

    please make a tutorial to learn the responsive template with html & css
    if you ve written any link it here

    tanks again

  7. Hi!

    This was easy to follow and understand for someone new to html5 css3 and javascript. I do have a question – my images seem to take quite a while to load, besides resizing them (I can’t afford to loose the quality) is there anything else I can do to have the images load quickly on website load?

    Thanks

  8. Great tutorial by the way! I added this into my website and it works perfectly in firefox when testing but not in chrome….is there a fix for this? Thank you look forward to your reply….very nice slideshow :)

  9. I also just checked IE and it does not function there either??? ANy conditional comments I can use to make this work or is it not compatable? I haven’t checked safari yet :) Keeping fingers crossed it can work I really love this slideshow :)

  10. Hi, Great tutorial on the slideshow. I am wondering something though. Your tutorial is not working when using Internet Explorer. I understand that this is because Internet Explorer(Worst enemy of web developers) does not recognize all HTML5 elements. Do you have a fix for this?

    Regards

    • Hello Christopher,
      IE is not the enemy, but it seems that it is the least-developed browser.
      To fix this problem with IE, please replace both instances of
      ctx.drawImage(img, 0, 0);
      to
      if (img) {
      ctx.drawImage(img, 0, 0);
      }
      Just in order to check if we have that image

  11. Hi,

    Awesome piece of code, but it isn’t working in Chrome…
    You can see the border of the slider, but it wont load the images…
    And in FF it does work
    Do you maybe have a solution for that?

    Kind regards

  12. Hi and thanks for the tutorial! I am brand new to web development so I have a very basic question for something I am having trouble with. Where do I put the js/script.js code? Do I copy and paste this into the html file? I feel like I should have been able to figure this out by now but I am having a lot of trouble with it. Thanks so much for your help!

    • Hi Chris,
      Keep the same folder structure as it should be (as it is in the package). The logic is simple: html code is in root, js files are in ‘js’ folder, css files are in ‘css’ folder.

  13. I would like to modify your solution to show multiple sliders on a page. These are set up dynamically by php and I can see how I might change css/html to accomodate this. However as a javascript ignoramus, I am struggling a bit. I could also see how I could dynamically setup javascript with separate variables for each slideshow (ie slideshow_nn, canvas_nn, ctx_nn, aImages_nn) then change the main function to invoke changeSlideTimer thus drawSwEffect a number of times, passing the appropriate ‘version’ of the various objects. My questions are:

    *are there other objects I should replicate?
    *Do I have to do anything to pixastatic (whose code I find unfathomable)
    *Is there a more elegant way of doing this that doesn’t involve dynamic javascript?

    Thanks Ron

    • Hi Ron,
      The best solution you could to do – to wrap this code into a separated jQuery plugin. Yes, it could have taken few hours, but it could help to isolate all the used variables into separate namespace.

  14. Andrew, forget my last post. I did make an attempt to make it work with multiple sites, but my ignorance of javascript and the complexity of pixastatic made it a struggle. I have found an alternative – simpler – solution.

  15. Hi Andrew,thanks for this tutorial, I’ve looked around and this the first that is easy to follow.

    One question, is there any way to have them fade between them? Right now it’s changes right after the brightness effect and creates a bumpy effect between the transitions.

    Thanks and keep up the great work!

    • Hi Dorian,
      Yes, of course you can use the fade effect between slides. You may also use one of other effects of Pixastic plugin, just check their website with the list of available effects.

  16. hi

    I have been trying to get your code to work on my site, I have transfered files that are need images are shown an canvas is showing but the images arent in the canvas and are all showing any ideas? also adding this to a fluid grid layout html5

    • Hi Doug,
      The best way is to compare the demo package with your result. You also can check if you have any JS errors on your page (using the Firebug plugin)

  17. Hi Andrew,

    I tried using your code on my website, but it doesn’t seem to work on Chrome (Version 34.0.1847.116 m). On Firefox it works ok. Please advice.

    Thank you

Leave a Reply