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>
<script>
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');


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


function redraw(mouse) {
    console.log('a');
    can.width = can.width;
    ctx.drawImage(img, 50, 50);
    ctx.beginPath();
    ctx.rect(0,0,800,800);
    ctx.arc(mouse.x, mouse.y, 40, 0, Math.PI*2, true)
    ctx.clip();
 
var image = new Image();
image.src ="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgs26KPdgc8iyiq4glSPJOmBvi-6ozaIEmXIXT8onCqCZ8nuru7JPCFyFsBur-st6-Mh0vFN80JK0xv1iGk04qZ8oPIJJSmkW2IN5ETGXRDKq6He4D3PCczAN7nIh8_8nGsJrUsFGg4gHU/s1600/ven-bw.jpg"
ctx.drawImage(image, 50 , 50);
 
}

var img = new Image();
img.src = 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXOHq6yHXKNdr07NP4RYijAoGhNTGcoCObKAdDqSM8EP7ANRY8OftZPBT_lB21MlE3YDlrUYYAUNytEwdEfUqQyXI0S7SGuSIlQTtZts9kmpwBGWmOfvnlnqjgZr8dvyXvX4wEYcl7XNA/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
    };
}

</script>

No comments:

Post a Comment