in HTML5

HTML5 Canvas Mouse Interaction Example

Below is the same example but rather that using the range slider it uses mouse movement on the canvas. I didn’t bother to do cross-browser stuff here so it will probably will not work right in Firefox because of the different way in which it deals with mouse position. Use Chrome for the optimal viewing experience. The code is below the example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var context;
var destx = 0;
var x = 0;
var ind;
var offset;

var photos = new Array();
for(var i=1; i<15; i++) {
    var im = new Image();
    im.src = "p" + i + ".jpg";
    photos.push(im);   
}

function init() {
    context = document.getElementById('canvas').getContext('2d');  
    canvas.addEventListener('mousemove', function(e) {
        x = e.offsetX / 670 * 8710;
    }, false);
    setInterval(loop, 1);
}

function loop() {
    destx += (x - destx) * 0.04;
    ind = Math.floor(destx/670);
    offset = destx % 670;
    context.drawImage(photos[ind], offset, 0, 670-offset, 503, 0, 0, 670-offset, 503);
    context.drawImage(photos[ind+1], 0, 0, 670, 503, 670-offset, 0, 670, 503);
}

Write a Comment

Comment

14 Comments

  1. from a html point of view, it would make more sense to build a structure, then styling the to make them inline, then using javascript to set some scroll position or what.

    performance should then be even better, with less cpu usage, and it would be very much more cross-platform.

  2. Works smoothly, but take a look at the CPU usage. I hava a Core i7 and it takes about half of the available processing power. HTML5 canvas was supposed to be a Flash killer in the sense of the resource consumption, but it turnes out it’s just another myth.

  3. Of course Flash will stay around but I don’t think canvas is a myth, Cemef, and I doubt Lee or Adobe do either. I think canvas and the rest of HTML5 are one awesome IDE away from taking a large chunk of business away from Flash, and I would be surprised if Adobe were not trying to develop it.

  4. In Firefox 5 it doesn’t work too :-/

    I had forgotten that I stopped having headaches when I started developing with AS…

  5. Thanks for the tutorial.

    Could you please show us how to create links of these images?
    Is there a way, either through placing a transparent png file over it or some other way to create a link to another page from this slideshow.
    Thanks,
    a’