按用户定义的角度

时间:2015-07-14 15:42:05

标签: javascript jquery angularjs html5 canvas

我想按用户定义的角度旋转图像,该角度将由输入滑块确定,范围从-90deg到90deg。基本上要求是在画布上拉直图像。

这是我尝试过使用angularjs

我的输入滑块和html:

Straighten: <input type="range" id="rotateImage" value="0" min="-90" max="90" step="1" ng-model="rotateAngle"/>
<div id="imageCanvas">
    <canvas id="canvas"></canvas>
</div>

我的控制员:

$scope.$watch('rotateAngle', function(newVal, oldVal) {
if (newVal) {
    rotate(newVal)
}
})

function rotate(rotAngle) {
console.log('rotate angle>> ', rotAngle);
var imageCanvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");
var gridWidth = imageCanvas.width,
    gridHeight = imageCanvas.height;
var deg = Math.PI / 180;

context.translate(gridWidth / 2, gridHeight / 2);
context.rotate(rotAngle * deg);
}

我也在画布上绘制一个网格以供参考

$scope.Straighten = function() {
var imageCanvas = document.getElementById("canvas"),
    gridWidth = imageCanvas.width,
    canvasWidth = gridWidth,
    gridHeight = imageCanvas.height,
    canvasHeight = gridHeight,
    gridPadding = 1;

var gridCanvas = $('<canvas id=gridLayer></canvas>').attr({
    width: canvasWidth,
    height: canvasHeight
}).appendTo('#imageCanvas');
var context = gridCanvas.get(0).getContext("2d");
drawGridBoard(gridWidth, gridHeight, gridPadding, context);
}

function drawGridBoard(gridWidth, gridHeight, gridPadding, context) {
for (var x = 0; x <= gridWidth; x += 40) {
    context.moveTo(0.5 + x + gridPadding, gridPadding);
    context.lineTo(0.5 + x + gridPadding, gridHeight + gridPadding);
}


for (var x = 0; x <= gridHeight; x += 40) {
    context.moveTo(gridPadding, 0.5 + x + gridPadding);
    context.lineTo(gridWidth + gridPadding, 0.5 + x + gridPadding);
}

context.strokeStyle = "blue";

context.setLineDash([15, 5]);
context.stroke();

}

我能够获得图像必须旋转的角度,但图像不会被掠过。 请帮忙

1 个答案:

答案 0 :(得分:0)

我几周以来一直在画布上工作。我正在更新你的旋转功能。也许你应该等到图像加载后才能绘制它。请在下面发布代码

function rotate(rotAngle) {
    console.log('rotate angle>> ', rotAngle);
    var canvas= document.getElementById("canvas"),
    context = canvas.getContext("2d");
    context.clearRect(0, 0, canvas.width, canvas.height); //Clear the canvas first

    var logoImg = new Image(); // Create instance of the Image class
    logoImg.src = item.image; // Tell the Image's relative url

    var gridWidth = canvas.width,
    var gridHeight = canvas.height;
    var deg = Math.PI / 180;


    logoImg.onload = function () {

                context.save();
                context.translate(gridWidth / 2, gridHeight / 2);

                context.rotate(rotAngle * Math.PI / 180);

                context.drawImage(logoImg, -(gridWidth / 2), -(gridHeight / 2));

                context.restore();
            };

}

上面的代码对我有用。