javascript - 为什么这个画布图像不能正确旋转?

时间:2014-02-13 02:41:08

标签: javascript html5-canvas

为什么此画布图像无法正确旋转?

当我单击旋转按钮时,图像会旋转,但会被奇怪地裁剪掉。我希望图像保持完整并简单地旋转。

重要提示:我不打算旋转div,我希望旋转实际图像。

见小提琴: http://jsfiddle.net/8V4V7/2/

代码:

function rotateBase64Image(base64data, callback) {
   console.log("what we get: " + base64data);

    var canvas = document.getElementById("dummyCanvas");
    var ctx = canvas.getContext("2d");

    var image = new Image();
    image.src = base64data;
    image.onload = function() {
        ctx.translate(image.width, image.height);
        ctx.rotate(Math.PI);
        ctx.drawImage(image, 0, 0);
        callback(canvas.toDataURL());
    };
}

修改 我需要在每次点击时将图像旋转90度。

我尝试了以下但是它不起作用:

ctx.rotate(Math.PI/2);

2 个答案:

答案 0 :(得分:1)

这对我有用(我在onload函数中指定了画布的高度和宽度):

function rotateBase64Image(base64data, callback) {
    console.log("what we get: " + base64data);

    var canvas = document.getElementById("dummyCanvas");
    var ctx = canvas.getContext("2d");

    var image = new Image();
    image.src = base64data;
    image.onload = function () {

        canvas.height = image.height;
        canvas.width = image.width;

        ctx.translate(image.width, image.height);
        ctx.rotate(Math.PI);
        ctx.drawImage(image, 0, 0);
        callback(canvas.toDataURL());
    };
}

修改

更新了每次点击旋转90度的功能(移除i中的i*Math.PI只旋转90度一次)

var i = 0;
function rotateBase64Image(base64data, callback) {
   console.log("what we get: " + base64data);

    var canvas = document.getElementById("dummyCanvas");
    var ctx = canvas.getContext("2d");

    var image = new Image();
    image.src = base64data;
    image.onload = function() {
        canvas.width = image.height;
        canvas.height = image.width;

       ctx.translate(canvas.width / 2, canvas.height / 2);
       i++;
       ctx.rotate(i*Math.PI/2);
       ctx.translate(-canvas.width / 2, -canvas.height / 2);

        ctx.drawImage(image, 0, 0);

    };
}

Updated Fiddle

答案 1 :(得分:0)

只是旋转的一些支持信息,特别是保存上下文以及如何围绕图像中心旋转。

var context = canvas.getContext('2d');
//save the context
//pushes a Matrix on the transformation stack
context.save();
context.translate(x, y); //where to put image
context.rotate(angle); //angle in degrees (i think...)
context.scale(scale); //optional scale
//rotate around center of image
context.drawImage(bitmap, -image.width / 2, -image.height / 2);
//or rotate around top left corner of image
context.drawImage(image, 0, 0);
//restore the canvas
//pop a matrix off the transformation stack
context.restore();

参考文献:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations

http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/