所以我在画布(700x600)内有一个图像(1020x736),我试图滚动/拖动图像,这样我就可以看到剩下的图像,除了我不想看到白色空间当我拖动图像时,当我到达图像边界时。
这是我的问题样本
黑色边框表示画布'边界。
到目前为止我的代码
var dragging = false;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var lastX;
var lastY;
var translated = 0;
canvas.onmousedown = function(e){
var evt = e || event;
dragging = true;
lastX = evt.offsetX;
lastY = evt.offsetY;
}
window.onmousemove = function(e){
var evt = e || event;
if(dragging){
var deltaX = evt.offsetX - lastX;
var deltaY = evt.offsetY - lastY;
context.translate(deltaX,deltaY);
lastX = evt.offsetX;
lastY = evt.offsetY;
draw();
}
}
function draw(){
var image = document.getElementById('img1');
context.drawImage(image,0,0);
}
canvas.onmouseup = function(e){
dragging = false;
}
window.onload = draw;
答案 0 :(得分:0)
从左上角绘图以防止图像远离画布
// canvas is the canvas
// img is the image you are drawing;
// posX and posY are the location (top left) that the image has been dragged to
x = Math.max( -(img.width - canvas.width), Math.min(0, posX));
y = Math.max( -(img.height - canvas.height), Math.min(0, posY));
ctx.drawImage(img, x, y);