我需要三个基本功能来操作图像:
我现在正在尝试缩放图片,但是如果我已经旋转它,它必须保留旋转的图像。
我需要用鼠标移动图像,同时保持缩放功能,旋转时旋转。
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;
}
});
答案 0 :(得分:8)
请参阅此处了解一些允许缩放和保持旋转的更改:
<强> Modified 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.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();
}
答案 1 :(得分:0)
查看Canvas 2D API的reference。有zooming (scale), translateing (moving origo)和rotating可用的方法。您所要做的就是将这些方法应用于画布的2D上下文:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Rotate the image 45 degrees
ctx.rotate(45 * (Math.PI/180));
// Move it 20 px to the left
ctx.translate(-20, 0);
// Then zoom in by 50%
ctz.scale(1.5, 1.5);
答案 2 :(得分:0)
Try this您可以使用缩放功能来实现缩放功能。