2 abu593218127 abu593218127 于 2016.04.22 14:33 提问

js 实现图片的旋转 结合css3的属性transform

我想在IE9下实现点击按钮进行图片的翻转,之前使用了滤镜,但有一个问题,图片在旋转时不是以图片中心为定点进行旋转,在网上查了css3的一个属性transform 可以实现以中心点进行旋转,但试了好多,都没实现,下面是滤镜实现代码:
/**
* 图片旋转
* @param id 图片id
* @param angle 旋转度数
* @param whence 旋转方向、从何处开始旋转
*/
rotate : function(id,angle,whence) {
var p = document.getElementById(id);
if (!whence) {
p.angle = ((p.angle==undefined?0:p.angle) + angle) % 360;
} else {
p.angle = angle;
}

    if (p.angle >= 0) {
        var rotation = Math.PI * p.angle / 180;
    } else {
        var rotation = Math.PI * (360+p.angle) / 180;
    }
    var costheta = Math.cos(rotation);
    var sintheta = Math.sin(rotation);

    if (document.all && !window.opera) {
        var canvas = document.createElement('img');

        canvas.src = p.src;
        canvas.height = p.height;
        canvas.width = p.width;

        canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')";
    } else {
        var canvas = document.createElement('canvas');
        if (!p.oImage) {
            canvas.oImage = new Image();
            canvas.oImage.src = p.src;
        } else {
            canvas.oImage = p.oImage;
        }

        canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height);
        canvas.style.height = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width);

        var context = canvas.getContext('2d');
        context.save();
        if (rotation <= Math.PI/2) {
            context.translate(sintheta*canvas.oImage.height,0);
        } else if (rotation <= Math.PI) {
            context.translate(canvas.width,-costheta*canvas.oImage.height);
        } else if (rotation <= 1.5*Math.PI) {
            context.translate(-costheta*canvas.oImage.width,canvas.height);
        } else {
            context.translate(0,-sintheta*canvas.oImage.width);
        }
        context.rotate(rotation);
        context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height);
        context.restore();
    }
    canvas.id = p.id;
    canvas.onmousewheel = p.onmousewheel;
    canvas.angle = p.angle;
    p.parentNode.replaceChild(canvas, p);
},
    ------------------------------------------------------------
    在css样式中:
    #imgDiv{
            -ms-transform:rotate(90deg); /* IE 9 */
    }
    这样可以实现旋转,
    但我想使用js进行动态左右旋转,求大神们赐教!谢谢

2个回答

showbo
showbo   Ds   Rxr 2016.04.22 14:40
已采纳
devmiao
devmiao   Ds   Rxr 2016.04.22 14:35
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!