Reputation: 155
I want to implement the following in HTML/JavaScript but don't really know where to start or even if there is already an existing function in one toolkit for this:
I have one image (e.g. a png) which is visible and a second image of the same size which is not visible. However, if I move the mouse pointer over the first image, the corresponding part from the second image shall be shown around the mouse cursor. So for example, if I move the mouse at position 100,100 on the first image, the section from 50,50 to 150,150 of the second image should be overlaid on the first image at position 50,50 to 150,150. I hope this is understandable.
Does anyone know, if there is already a library which contains this functionality? I've already searched for this on the internet but found nothing. However, I do not really know what keywords to search for. So if someone knows a keyword to search for, I would be appreciate hints as well.
Alternatively, Can you give me a cue how could I grep the part of the second image and display it at the mouse position? I was thinking that canvas might be used but I am not sure how to.
Thank you very much and best regards
Tobias
Upvotes: 3
Views: 1986
Reputation: 4497
This can be done with Vanilla JS or JQuery. Basic idea behind it is to wrap the image in a container with position:relative
and listen to mouse movement on it. A second <div>
with position:absolute
will receive the coordinates of the mouse pointer with its background position set to match the current mouse offset.
The posted code is just to give an idea how this would look like and needs to be extended to properly handle the edges of the image.
$(".hover-container").on("mousemove", function (e) {
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
var picHeight = $('.hover-image').height();
var picWidth = $('.hover-image').height();
$('.hover-image')
.css("left", relX - 50 + "px")
.css("top", relY - 50 + "px")
.css("background-position", (picWidth-relX-50) + "px "
+ (picHeight-relY-50) + "px")
});
.hover-container {
position: relative;
}
.hover-image {
position: absolute;
width: 100px;
height: 100px;
background: url(https://i.imgur.com/Hp5pUVA.jpg);
background-position: 0 0;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="hover-container">
<img class="hover-over" src="https://i.imgur.com/j0yhQez.jpg"/>
<div class="hover-image"></div>
</div>
Upvotes: 6