我想要的是,仅当宽度或高度大于画布时才能拖动到位置。保持完整。
下面的代码可以很好地工作(使图像可拖动),但是如果图像小于画布(宽度和/或高度),它将删除全部填充。
var posX = 0, posY = 0;
var lastX, lastY;
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
};
}
}
function drowImageFill(ctx, canvas, img){
//ctx.clearRect(0, 0, canvas.width, canvas.height);
//detect closet value to canvas edges
if( img.height / img.width * canvas.width > canvas.height)
{
// fill based on less image section loss if width matched
var width = canvas.width;
var height = img.height / img.width * width;
offset = (height - canvas.height) / 2;
ctx.drawImage(img, 0, -offset, width, height);
}
else
{
// fill based on less image section loss if height matched
var height = canvas.height;
var width = img.width / img.height * height;
offset = (width - canvas.width) / 2;
ctx.drawImage(img, -offset , 0, width, height);
}