Canvas How to - Rotate an image in animation








Question

We would like to know how to rotate an image in animation.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--   w  w w . ja  v  a2s.  c  o m-->
var smile = new Image();
smile.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPAgMAAABGuH3ZAAAAAXNSR0IArs4c6QAAAAlQTFRFAAANAAAA/PxQjQj98QAAAAF0Uk5TAEDm2GYAAAABYktHRACIBR1IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH2gwXFQ4DaigKYQAAADhJREFUCNdjYBANYGBgzFrKwMC2apUDg1TUtAkQImvVqiXoROaqlUsYpLKWAZVMjZoA0QHWCzIFAJGSGI4XxkZDAAAAAElFTkSuQmCC';
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
context.fillStyle = 'silver';
context.fillRect(0, 0, canvas.width, canvas.height);
var theta = 0;
drawStep = function() {
  context.save();
  context.translate(150, 75);
  context.rotate(theta);
  context.drawImage(smile, -7, -7);
  context.restore();
  theta += Math.PI / 180;
  setTimeout(drawStep, 16);
};
setTimeout(drawStep, 16);
}//]]>  
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: