问题
I'm working on a t-shirt designer for a client of mine and I made it using html5 canvas. The shirt designer is now finished but he requested I add a magnifying glass (something like this: http://mlens.musings.it/). I've found a lot of similar scripts out there, however, they all seem to have one thing in common they use a small and a large image. Using canvas, however, I have a different scenario and have been stumped on how I can add a magnifying glass to magnify where ever the cursor is on canvas.
Are there any scripts that exist that can get this done? or what other options would I have?
回答1:
Let's just draw the canvas to another canvas but scaled.
fiddle example
context.drawImage
allows us to specify how much of the origin canvas we want to get and how big to draw it on the destination canvas. So to do a times 2 zoom we just draw the origin canvas twice the size to the destination canvas.
var main = document.getElementById("main");
var zoom = document.getElementById("zoom");
var ctx = main.getContext("2d")
var zoomCtx = zoom.getContext("2d");
var img = new Image();
img.src = "http://astrobioloblog.files.wordpress.com/2011/10/duck-1.jpg"
img.onload = run;
function run(){
ctx.drawImage(img,0,0);
}
main.addEventListener("mousemove", function(e){
//console.log(e);
zoomCtx.drawImage(main, e.x, e.y, 200, 100, 0,0, 400, 200);
console.log(zoom.style);
zoom.style.top = e.pageY + 10+ "px"
zoom.style.left = e.pageX +10+ "px"
zoom.style.display = "block";
});
main.addEventListener("mouseout", function(){
zoom.style.display = "none";
});
来源:https://stackoverflow.com/questions/23971717/magnifying-glass-that-follows-cursor-for-canvas