2

i have create the canvas which has different background and over that another image in the middle of canvas,now i want to rotate that image at 90 at its place only,i tried lots of code but get nothing as result. how can i do that..??

<style type="text/css" media="screen">
    canvas, img { display:block; margin:1em auto; border:1px solid black; }
    canvas { background:url(http://i.dailymail.co.uk/i/pix/2013/11/11/article-2500617-007F32C500000258-970_306x423.jpg) }
  </style>
</head><body>
<button id="clockwise">Rotate right</button>
<canvas width="300" height="300"></canvas>
<img>
<script type="text/javascript" charset="utf-8">
  var can = document.getElementsByTagName('canvas')[0];
  var ctx = can.getContext('2d');
  ctx.strokeStyle = '#f00';
  ctx.lineWidth   = 6;
  ctx.lineJoin    = 'round';
  ctx.strokeRect(40,100,150,100);
     var angleInDegrees=0;
  var img = document.getElementsByTagName('img')[0];
img.src="http://media1.santabanta.com/full1/Miscellaneous/Cartoon%20Characters/cartoon-characters-47a.jpg";
  ctx.drawImage(img,40,100,150,100);

 function drawRotated(degrees){
        ctx.clearRect(40,100,150,100);
        ctx.save();
        ctx.translate(40,100,150,100);
        ctx.rotate(degrees*Math.PI/180);
        ctx.drawImage(img,-img.width/2,-img.width/2);
        ctx.restore();
    }
 $("#clockwise").click(function(){ 
        angleInDegrees+=30;
        drawRotated(angleInDegrees);
    });
</script>

</body></html> 
  • Your code looks OK to me; drawImage should respect the rotated context and render at an angle. Can you elaborate on what's going wrong? – Dave Jan 18 '15 at 17:56
  • @ Dave on click image is not rotating., don't getting what's the problem – Himani Verma Jan 18 '15 at 18:00
  • Works fine for me. Here, I jsfiddled it for you: http://jsfiddle.net/krv93wzh/ – Dave Jan 18 '15 at 18:03
  • @ Dave it is overlapping the background image, why it in not rotating in its red color box only..?? – Himani Verma Jan 18 '15 at 18:06
  • Oh right. That's because you didn't set the image size in your second drawImage call, so it's drawing at full size. Maybe this change is more what you expected? http://jsfiddle.net/krv93wzh/1/ (I also made it clear the entire canvas and draw the box again after the rotation) – Dave Jan 18 '15 at 18:08
  • thank you Dave,now it's working like what i want thank you so much. – Himani Verma Jan 18 '15 at 18:12
  • just one more thing, how can i hide that large image i'am getting below the canvas through tag.. ?? – Himani Verma Jan 18 '15 at 18:13
  • Here's a general discussion http://stackoverflow.com/questions/9614622/equivalent-of-jquery-hide-to-set-visibility-hidden (it relates to jQuery, but then you're already using jQuery anyway. It's not hard to show/hide without jQuery though) – Dave Jan 18 '15 at 18:19

0 Answers0