有关允许缩放和保持旋转的一些更改,请参见此处:
修改过的小提琴
您无需为此使用保存/恢复,因为您不断更改缩放和旋转。让他们积累。好的,我错过了你也想翻译画布。在那种情况下,积累起来会很复杂,所以在这种情况下,一定要使用保存和恢复:)
但是,您可以重构代码,以便在一个位置进行旋转和缩放,并在鼠标移动事件中移动。
将翻译移动到全局(或在这里,移动到通常在全局中的图像加载),这样你就有了一个中心起点。
进行了以下修改(参见上面更新的小提琴):
// set delta for zoom and keep track of current zoom
var zoomDelta = 0.1;
var currentScale = 1;
// set delta for rotation and keep of current rotation
var currentAngle = 0;
var startX, startY, isDown = false;
简化负载(我建议window.onload
改为这样做):
jQuery('#carregar').click(function () {
element.translate(canvas.width / 2, canvas.height / 2);
// the new refactored function common to all steps
drawImage();
jQuery('#canvas').attr('data-girar', 0);
this.disabled = true;
});
旋转函数现在简化为:
jQuery('#giraresq').click(function () {
angleInDegrees = 90;
currentAngle += angleInDegrees;
drawImage()
});
jQuery('#girardir').click(function () {
angleInDegrees = -90;
currentAngle += angleInDegrees;
drawImage()
});
缩放功能:
jQuery('#zoomIn').click(function () {
currentScale += zoomDelta;
drawImage()
});
jQuery('#zoomOut').click(function () {
currentScale -= zoomDelta;
drawImage();
});
要移动画布,我们需要跟踪鼠标的向下、向上和移动:
canvas.onmousedown = function (e) {
var pos = getMousePos(canvas, e);
startX = pos.x; // store current position
startY = pos.y;
isDown = true; // mark that we are in move operation
}
canvas.onmousemove = function (e) {
if (isDown === true) {
var pos = getMousePos(canvas, e);
var x = pos.x;
var y = pos.y;
// translate difference from now and start
element.translate(x - startX, y - startY);
drawImage();
// update start positions for next loop
startX = x;
startY = y;
}
}
// reset move operation status
canvas.onmouseup = function (e) {
isDown = false;
}
重构后的函数现在完成了所有的清除、旋转和缩放:
function drawImage() {
clear();
element.save(); // as we now keep track ourselves of angle/zoom due to
// translation, we can use save/restore
element.scale(currentScale, currentScale);
element.rotate(currentAngle * Math.PI / 180);
element.drawImage(image, -image.width * 0.5, -image.width * 0.5);
element.restore();
}