<强> JSFiddle
我有 JQuery 脚本,允许我将图像拖动到 Canvas 中。请参阅随附的 JSFiddle 引用。
我的问题是,假设我将图像拖到左侧,我可以获得图像的当前状态,我们可以看到多少部分?因此,下次当我在 Canvas 中加载图像时,它应该首先显示上次可见的部分
var drag, canvas, ctx;
var posX = 0, posY = 0;
var lastX, lastY;
$(document).ready(function(){
canvas=document.getElementById("canvas");
ctx=canvas.getContext("2d");
var image=document.createElement("img");
image.onload=function(){
canvas.width = 600;
canvas.height = 200;
ctx.drawImage(image,posX,posY);
init();
}
image.src="http://peach.blender.org/wp-content/uploads/poster_rodents_big.jpg";
function init(){
canvas.addEventListener('mousedown', function(){
drag = true;
lastX=null;
lastY=null;
});
document.addEventListener('mouseup', function(){
drag = false;
});
document.addEventListener('mousemove', function(evt) {
if(drag){
var mousePos = getMousePos(canvas, evt);
var x = mousePos.x;
var y = mousePos.y;
ctx.clearRect(0,0,canvas.width,canvas.height);
if(lastX && lastY){
posX += x-lastX;
posY += y-lastY;
if(posX>0) posX=0;
if(posY>0) posY=0;
if(posX<-image.width+canvas.width) posX = -image.width+canvas.width;
if(posY<-image.height+canvas.height) posY = -image.height+canvas.height;
ctx.drawImage(image,posX,posY);
}
lastX=x;
lastY=y;
}
}, false);
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
});
最佳答案
不确定这是否是您所需要的,但为什么不在每次图像移动时将 posX 和 posY 存储在 cookie 或 localStorage 中。然后在页面加载时检索存储的位置。类似这样的事情:
//Store the position :
localStorage.setItem('position', JSON.stringify({x:posX,y:posY}));
//Top of your script
var lastKnown = localStorage.getItem('position');
if(lastKnown) {
var parsed = JSON.parse(lastKnown);
var posX = parsed.x, posY = parsed.y;
} else {
var posX = 0, posY = 0;
}
您可以找到修改后的Fiddle here
关于javascript - 获取图像可见区域状态以将 Canvas 中的图像设置在先前拖动的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028345/