javascript – 围绕画布中央旋转图像

前端之家收集整理的这篇文章主要介绍了javascript – 围绕画布中央旋转图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在画布上做我的第一个图像动画.我想让图片旋转,但我的代码中的东西不正确.有任何想法吗?这都在一个 jquery文档中准备好:
  1. var canvas = document.getElementById('logobg1');
  2. var ctx = canvas.getContext('2d');
  3.  
  4. var img = new Image(); // Create new Image object
  5. img.src = 'images/containerbg.png'; // Set source path // set img src
  6.  
  7. img.onload = function(){ // when image loads
  8. ctx.drawImage(img,0);
  9. setInterval(function() {
  10. ctx.save();
  11. ctx.clearRect(-ctx.canvas.width/2,-ctx.canvas.height/2,ctx.canvas.width,ctx.canvas.height);
  12. ctx.drawImage(img,0);
  13. ctx.translate(ctx.canvas.width/2,ctx.canvas.height/2); // set canvas context to center
  14. ctx.rotate(Math.PI / 180 * 0.5); // 1/2 a degree
  15. ctx.restore();
  16. },16);
  17. }

解决方法

只需更改代码的顺序,即
  1. ctx.rotate(...);
  2.  
  3. ctx.drawImage(...);

见一个工作示例http://jsbin.com/owuyiq/

  1. $(function () {
  2. var canvas = document.getElementById('logobg1');
  3. var ctx = canvas.getContext('2d');
  4. var img = new Image();
  5.  
  6. var ang = 0; //angle
  7. var fps = 1000 / 25; //number of frames per sec
  8. img.onload = function () { //on image load do the following stuff
  9. canvas.width = this.width << 1; //double the canvas width
  10. canvas.height = this.height << 1; //double the canvas height
  11. var cache = this; //cache the local copy of image element for future reference
  12. setInterval(function () {
  13. ctx.save(); //saves the state of canvas
  14. ctx.clearRect(0,canvas.width,canvas.height); //clear the canvas
  15. ctx.translate(cache.width,cache.height); //let's translate
  16. ctx.rotate(Math.PI / 180 * (ang += 5)); //increment the angle and rotate the image
  17. ctx.drawImage(img,-cache.width / 2,-cache.height / 2,cache.width,cache.height); //draw the image ;)
  18. ctx.restore(); //restore the state of canvas
  19. },fps);
  20. };
  21.  
  22. img.src = 'http://i.stack.imgur.com/Z97wf.jpg?s=128'; //img
  23. });

猜你在找的JavaScript相关文章