我用
CSS3看过一些很酷的图像遮罩和其他效果.只使用CSS3我们可以在下面的代码中看到这种效果,或者看到工作小提琴.
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); ctx.beginPath(); ctx.rect(0,500,500); ctx.arc(mouse.x,mouse.y,70,Math.PI*2,true) ctx.clip(); ctx.drawImage(img2,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 }; }
解决方法
这是使用背景图像的替代方法.它更灵活,你得到一个圆形(或任意形状)视口:
http://jsfiddle.net/maackle/66uCs/
HTML
<div class="masker"> <img class="base" src="http://lorempixel.com/400/400/cats/1" /> <div class="overlay"></div> </div>
CSS
.masker { position: relative; } .overlay { position: absolute; display: none; width: 100px; height: 100px; border-radius: 50%; background: url(http://lorempixel.com/400/400/cats/2) no-repeat; }
jQuery 1.10.1
$('.masker').on('mousemove',function (e) { var r,x,y,top,left,bottom,right,attr,$base,$overlay; r = 100; $base = $(this).find('.base'); $overlay = $(this).find('.overlay'); x = e.pageX - $base.offset().left; y = e.pageY - $base.offset().top; top = y - r / 2; left = x - r / 2; if (x < 0 || y < 0 || x > $base.width() || y > $base.height()) { $overlay.hide(); } else { $overlay.show().css({ 'background-position': '' + (-left) + 'px ' + (-top) + 'px','left': left,'top': top }); } }); //just for good measure $('.masker').on('mouSEOut',function (e) { $(this).find('.overlay').hide(); });