WEBCONE representing: JS - canvas - hover part of image

I already published code of hovering part of image, but that code was in HTML5 and CSS(Hovering part of image using CSS and HTML5). This code is much better. It is in written in JS and HTML5. I couldn't find example of that code on the web so I have to make my own. You can use this code for example when you client want that you hover just part of image like in my case = ), or for everything else that you need. I hope this code will help you.

Scroll down to see result.

Here is the code:
<canvas height="800" id="canvas" width="800"></canvas>
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');

can.addEventListener('mousemove', function(e) {
    var mouse = getMouse(e, can);
}, false);

function redraw(mouse) {
    can.width = can.width;
    ctx.drawImage(img, 50, 50);
    ctx.arc(mouse.x, mouse.y, 40, 0, Math.PI*2, true)
var image = new Image();
image.src ="http://4.bp.blogspot.com/-aEIckV2vbug/UYu1HBXHPkI/AAAAAAAAADs/mGxVKwPgEdY/s1600/ven-bw.jpg"
ctx.drawImage(image, 50 , 50);

var img = new Image();
img.src = 'http://2.bp.blogspot.com/-bkJAtUiuLuk/UYu1A0hC8jI/AAAAAAAAADk/XTPjgec5pCw/s1600/ven.jpg';
img.onload = function() {
redraw({x: -500, y: -500})

// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas

function getMouse(e, canvas) {
     var element = canvas,
         offsetX = 0,
         offsetY = 0,
         mx, my;

    // Compute the total offset. It's possible to cache this if you want
    if (element.offsetParent !== undefined) {
        do {
            offsetX += element.offsetLeft;
            offsetY += element.offsetTop;
        } while ((element = element.offsetParent));

    mx = e.pageX - offsetX;
    my = e.pageY - offsetY;

    return {
        x: mx,
        y: my


No comments:

Post a Comment