微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

HTML5画布旋转图片

jQuery('#carregar').click(function(){
var canvas  = document.getElementById('canvas');
var image   = document.getElementById('image');
var element = canvas.getContext("2d");
element.clearRect(0,canvas.width,canvas.height);
element.drawImage(image,300,300);
});

jsfiddle.net/braziel/nWyDE/

我有一个问题,将图像向右或向左旋转90°。

我在画布上使用一个图像,同一个屏幕将有几个画布等于示例,但我把它尽可能接近项目。

我问,当我点击“向左旋转”和“向右旋转”时,如何将图像向左或向右旋转90°?

我试过几个代码在互联网上,但没有工作。

解决方法

你可以使用canvas’context.translate& context.rotate来旋转你的图像

这里有一个函数来绘制旋转了指定度数的图像:

function drawRotated(degrees){
    context.clearRect(0,canvas.height);

    // save the unrotated context of the canvas so we can restore it later
    // the alternative is to untranslate & unrotate after drawing
    context.save();

    // move to the center of the canvas
    context.translate(canvas.width/2,canvas.height/2);

    // rotate the canvas to the specified degrees
    context.rotate(degrees*Math.PI/180);

    // draw the image
    // since the context is rotated,the image will be rotated also
    context.drawImage(image,-image.width/2,-image.width/2);

    // we’re done with the rotating so restore the unrotated context
    context.restore();
}

这里是代码和小提琴:http://jsfiddle.net/m1erickson/6ZsCz/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    var angleIndegrees=0;

    var image=document.createElement("img");
    image.onload=function(){
        ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
    }
    image.src="houseicon.png";

    $("#clockwise").click(function(){ 
        angleIndegrees+=30;
        drawRotated(angleIndegrees);
    });

    $("#counterclockwise").click(function(){ 
        angleIndegrees-=30;
        drawRotated(angleIndegrees);
    });

    function drawRotated(degrees){
        ctx.clearRect(0,canvas.height);
        ctx.save();
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(degrees*Math.PI/180);
        ctx.drawImage(image,-image.width/2);
        ctx.restore();
    }


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas><br>
    <button id="clockwise">Rotate right</button>
    <button id="counterclockwise">Rotate left</button>
</body>
</html>

原文地址:https://www.jb51.cc/html5/169886.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。