I've seen some cool image masking and other effects with CSS3. Using only CSS3 can we achieve this effect seen in the code below or see working fiddle.
http://jsfiddle.net/s6u9a/
HTML
<canvas id="canvas1" width="400" height="400"></canvas>
Javascript
var can = document.getElementById('canvas1');
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, 0, 0);
ctx.beginPath();
ctx.rect(0,0,500,500);
ctx.arc(mouse.x, mouse.y, 70, 0, Math.PI*2, true)
ctx.clip();
ctx.drawImage(img2, 0, 0);
}
var img = new Image();
img.onload = function() {
redraw({x: -450, y: -500})
}
img.src = 'http://placekitten.com/400/400';
var img2 = new Image();
img2.onload = function() {
redraw({x: -450, y: -500})
}
img2.src = 'http://placekitten.com/400/395';
function getMouse(e, canvas) {
var element = canvas,
offsetX = 0,
offsetY = 0,
mx, my;
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
};
}
Here's a solution that uses mostly CSS -- you do need some Javascript to detect the mouse position. Note that this gives you a square viewport instead of a circle, but if CSS ever adds circle() alongside rect() for the clip property, you will have that option:
http://jsfiddle.net/maackle/Yc2b4/
<div class="masker">
<img class="base" src="http://lorempixel.com/400/400/cats/1" />
<img class="overlay" src="http://lorempixel.com/400/400/cats/2" />
</div>
.masker {
position: relative;
}
.overlay {
position: absolute;
top: 0;
left: 0;
display: none;
}
$('.masker img').on('mousemove', function(e) {
var r, x, y, top, left, bottom, right, attr, $overlay;
r = 100;
x = e.pageX - $(this).offset().left;
y = e.pageY - $(this).offset().top;
top = y - r/2;
left = x - r/2;
bottom = y + r/2;
right = x + r/2;
attr = 'rect('+(top)+'px, '+(right)+'px, '+(bottom)+'px, '+(left)+'px)';
$overlay = $('.masker .overlay');
$overlay.show().css({clip: attr});
});
$('.masker img').on('mouseout', function(e) {
$('.masker .overlay').hide();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With