javascript - 如何在 Canvas 中旋转图像

标签 javascript angularjs html canvas

我用 https://github.com/petalvlad/angular-canvas-ext 构建了一个 Canvas 项目

    <canvas width="640" height="480" ng-show="activeateCanvas" ap-canvas src="src" image="image" zoomable="true" frame="frame" scale="scale" offset="offset"></canvas>

我能够使用以下代码成功缩放和平移图像

        scope.zoomIn = function() {
          scope.scale *= 1.2;
        }

        scope.zoomOut = function() {
          scope.scale /= 1.2;
        }

另外我想旋转图像。我可以使用哪个库来获得任何帮助以及如何在 angularjs 中做到这一点。

最佳答案

您可以使用 JavaScript 中的 context.rotate 函数旋转图像。 以下是如何执行此操作的示例:

var canvas = null;
var ctx = null;
var angleInDegrees = 0;
var image;
var timerid;

function imageLoaded() {
    image = document.createElement("img");
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext('2d');
    image.onload = function() {
        ctx.drawImage(image, canvas.width / 2 - image.width / 2, canvas.height / 2 - image.height / 2);
    };
    image.src = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT7vR66BWT_HdVJpwxGJoGBJl5HYfiSKDrsYrzw7kqf2yP6sNyJtHdaAQ";
}

function drawRotated(degrees) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate(degrees * Math.PI / 180);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
    ctx.restore();
}
<button onclick="imageLoaded();">Load Image</button>
<div>
    <canvas id="canvas" width=360 height=360></canvas><br>

    <button onclick="javascript:clearInterval(timerid);
            timerid = setInterval(function() {
                angleInDegrees += 2;
                drawRotated(angleInDegrees);
            }, 100);">
        Rotate Left
    </button>

    <button onclick="javascript:clearInterval(timerid);
            timerid = setInterval(function() {
                angleInDegrees -= 2;
                drawRotated(angleInDegrees);
            }, 100);">
        Rotate Right
    </button>
</div>

关于javascript - 如何在 Canvas 中旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33124360/

相关文章:

javascript - 使用 AngularJs 和 Firebase 无限滚动

javascript - 如何根据条件为 ng-model 赋值

javascript - 可以在应用程序中多次添加的主干 View 中的事件

css - 具有绝对位置的页脚 - 响应式设计

javascript - 如何设置 Http 请求 header 中的值

javascript - 为什么\n 和 <br> 不能在字符串中使用?

Javascript 强制更改出现在页面完全加载之前

html - 在选择事件 Django 模板上

javascript - 将“直引号”转换为 “Curly Quotes”

javascript - :confirm option in Rails being ignored while using Rails 3 and jQuery UJS