Magnifying glass that follows cursor for canvas

99封情书 提交于 2021-02-07 14:23:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!