水平旋转图像点击

时间:2014-03-04 15:03:10

标签: javascript jquery css css3

这是垂直的,但我试图通过点击图像水平旋转。无法弄清楚这一点!或者也可以采用更简单的方法。

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Flip Image</title>
        <style>
            canvas{border:1px solid #333}
            img{display:none;}
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">      </script>
        <script type="text/javascript">
            $(window).load(function(){

                var immagine = $('img')[0]
                alt=immagine.height
                lar=immagine.width
                $('<canvas width="'+lar+'" height="'+alt+'"></canvas>').appendTo('body')
                var ca=$('canvas').get(0)
                ctx=ca.getContext('2d')
                ctx.drawImage(immagine, 0, 0);

                $('canvas').click(function(){
                    ctx.translate(lar-1, alt-1);
                    ctx.rotate(Math.PI);
                    ctx.drawImage(immagine, 0, 0, lar, alt);
                 })

            })
        </script>
    </head>
    <body>
        <!-- onclick rotate image horizontally-->
        <img src="myimage.jpg">

        <br><Br>

    </body>
</html>

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以通过简单的数学逻辑将图像旋转到任意角度。例如,如果要将图像旋转到90度。只需使用:

ctx.rotate(90 * Math.PI/180);

您可以在上面的代码中设置所需的角度并旋转图像。

<强>更新 我根据您的需要添加一些代码。适用于画布点击,这将在一个方向旋转图像。

var angleInDegrees=0;

$('canvas').click(function(){
   angleInDegrees+=90;
    drawRotated(angleInDegrees);
 })
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.width/2);
    ctx.restore();
}

答案 1 :(得分:0)

我同意Rajesh的评论,你可以设置你的角度,然后根据之前的翻译进行旋转。我有时喜欢在画布上使用webkit。这是一个使用CSS webkit水平旋转的小提琴,在我看来它更简单。 Horizontal Rotation Using Webkit

.rotate  img{
-webkit-transform: rotateY(180deg);   
-webkit-transition: -webkit-transform 1s, z-index 0s 0.25s;
z-index: -2; }

答案 2 :(得分:0)

检查jsfiddle是否有帮助

.imageRotateHorizontal{
    -moz-animation: spinHorizontal .8s infinite linear;
    -o-animation: spinHorizontal .8s infinite linear;    
    -webkit-animation: spinHorizontal .8s infinite linear;
    animation: spinHorizontal .8s infinite linear;
}

@keyframes spinHorizontal {
    0% { transform: rotateY(0deg); }
    100% { transform: rotateY(360deg); }
}

MSDN