我有一种情况,ImageData
即使在平移图像之后,我也需要在画布内获得全部内容。
提前致谢
小提琴中的示例:https ://jsfiddle.net/z46cvm9h/
<canvas id="canvas"></canvas>
<button onclick="showImage()">
Show panned Image
</button>
<img id="image" src='' />
var context = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 300;
var global = {
scale : 1,
offset : {
x : 0,
y : 0,
},
};
var pan = {
start : {
x : null,
y : null,
},
offset : {
x : 0,
y : 0,
},
};
function draw() {
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
context.translate(pan.offset.x, pan.offset.y);
context.beginPath();
context.rect(50, 50, 100, 100);
context.fillStyle = 'skyblue';
context.fill();
context.beginPath();
context.arc(350, 250, 50, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
}
draw();
canvas.addEventListener("mousedown", startPan);
canvas.addEventListener("mouseleave", endPan);
canvas.addEventListener("mouseup", endPan);
function startPan(e) {
canvas.addEventListener("mousemove", trackMouse);
canvas.addEventListener("mousemove", draw);
pan.start.x = e.clientX;
pan.start.y = e.clientY;
}
function endPan(e) {
canvas.removeEventListener("mousemove", trackMouse);
pan.start.x = null;
pan.start.y = null;
global.offset.x = pan.offset.x;
global.offset.y = pan.offset.y;
}
function trackMouse(e) {
var offsetX = e.clientX - pan.start.x;
var offsetY = e.clientY - pan.start.y;
pan.offset.x = global.offset.x + offsetX;
pan.offset.y = global.offset.y + offsetY;
}
function showImage(){
document.getElementById('image').src = canvas.toDataURL();
}
PS:JSFiddle是为了演示,我不能把确切的场景放到JSFiddle中。在应用程序中,我平移图像,然后使用鼠标使用mousedown
和mousemove
事件在画布上绘制一些东西。在mouseup
活动中,我需要拥有ImageData
我绘制的完整图像,但是当使用 时getImageData
,我只会让图像出现在画布上。平移的图像被裁剪为画布大小。