HTML5画布旋转图片

前端之家收集整理的这篇文章主要介绍了HTML5画布旋转图片前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. jQuery('#carregar').click(function(){
  2. var canvas = document.getElementById('canvas');
  3. var image = document.getElementById('image');
  4. var element = canvas.getContext("2d");
  5. element.clearRect(0,canvas.width,canvas.height);
  6. element.drawImage(image,300,300);
  7. });

jsfiddle.net/braziel/nWyDE/

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

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

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

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

解决方法

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

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

  1. function drawRotated(degrees){
  2. context.clearRect(0,canvas.height);
  3.  
  4. // save the unrotated context of the canvas so we can restore it later
  5. // the alternative is to untranslate & unrotate after drawing
  6. context.save();
  7.  
  8. // move to the center of the canvas
  9. context.translate(canvas.width/2,canvas.height/2);
  10.  
  11. // rotate the canvas to the specified degrees
  12. context.rotate(degrees*Math.PI/180);
  13.  
  14. // draw the image
  15. // since the context is rotated,the image will be rotated also
  16. context.drawImage(image,-image.width/2,-image.width/2);
  17.  
  18. // we’re done with the rotating so restore the unrotated context
  19. context.restore();
  20. }

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

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
  5. <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  6.  
  7. <style>
  8. body{ background-color: ivory; }
  9. canvas{border:1px solid red;}
  10. </style>
  11.  
  12. <script>
  13. $(function(){
  14.  
  15. var canvas=document.getElementById("canvas");
  16. var ctx=canvas.getContext("2d");
  17.  
  18. var angleInDegrees=0;
  19.  
  20. var image=document.createElement("img");
  21. image.onload=function(){
  22. ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
  23. }
  24. image.src="houseicon.png";
  25.  
  26. $("#clockwise").click(function(){
  27. angleInDegrees+=30;
  28. drawRotated(angleInDegrees);
  29. });
  30.  
  31. $("#counterclockwise").click(function(){
  32. angleInDegrees-=30;
  33. drawRotated(angleInDegrees);
  34. });
  35.  
  36. function drawRotated(degrees){
  37. ctx.clearRect(0,canvas.height);
  38. ctx.save();
  39. ctx.translate(canvas.width/2,canvas.height/2);
  40. ctx.rotate(degrees*Math.PI/180);
  41. ctx.drawImage(image,-image.width/2);
  42. ctx.restore();
  43. }
  44.  
  45.  
  46. }); // end $(function(){});
  47. </script>
  48.  
  49. </head>
  50.  
  51. <body>
  52. <canvas id="canvas" width=300 height=300></canvas><br>
  53. <button id="clockwise">Rotate right</button>
  54. <button id="counterclockwise">Rotate left</button>
  55. </body>
  56. </html>

猜你在找的HTML5相关文章