我需要三个基本函数来操作图像:
- 旋转图像;
- 缩放图像;
- 移动图像。
我现在正在尝试缩放图片,但如果我旋转了它,它必须保留旋转的图像。
我需要用鼠标移动图像,同时保持缩放和旋转(如果旋转)的功能。
jQuery('#zoom').click(function(){
element.clearRect(0, 0, canvas.width, canvas.height);
larguraNova = ( canvasWidth + (escalaPixel * valorZoom) );
if(larguraNova > canvasWidth){
/* passo a nova largura que é igual a altura */
novosDadosWH = larguraNova;
novosDadosTRBL = ( ( larguraNova - canvasWidth ) / 2 ) ;
} else {
/* passo o valor original */
novosDadosH = novosDadosW = canvasWidth;
}
});
<强> Fiddle
最佳答案
请参阅此处了解一些允许缩放和保持旋转的更改:
<强> Modified fiddle
您不需要为此使用保存/恢复,因为您会不断更改缩放和旋转。让它们积累起来。 好吧,我错过了您也想翻译 Canvas 。在这种情况下,积累会很复杂,所以在这种情况下请使用保存和恢复:)
但是,您可以重构代码,以便在一处进行旋转和缩放,并在鼠标移动事件中进行移动。
将翻译移动到全局(或者像这里一样,移动到通常位于全局的图像加载),这样你就有了一个中心起点。
进行了以下修改(请参阅上面更新的 fiddle ):
// 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 ,我们需要跟踪鼠标的向下、向上和移动:
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();
}
关于jquery - 旋转 + 缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426080/