www.webdeveloper.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2006
    Posts
    72

    Question Canvas: Why I can't rotate an image?

    Why This code not rotate the image?

    Code:
    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Image to use:</p>
    <img id="scream" src="http://www.webdeveloper.com/forum/images/webdev-logo2.gif" alt="The Scream" width="220" height="277">
    
    <p>Canvas:</p>
    <canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>
    
    <script>
    
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var img=document.getElementById("scream");
    ctx.drawImage(img,10,10,150,180);
    ctx.rotate(30*Math.PI/180);
    </script>
    
    </body>
    </html>
    base on the code on:
    http://www.w3schools.com/tags/tryit....vas_drawimage2

    Thanks
    Nadav

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    You have to call ctx.rotate() before calling ctx.drawImage() as the rotation only affects drawings made after the rotation has been done.

  3. #3
    Join Date
    May 2006
    Posts
    72
    Thanks!

    I need to rotate part of the image, why does it not work with putImageData?

    for example:
    Code:
    <!DOCTYPE html>
    <html>
    <body>
    
    <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>
    
    <script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.fillStyle="red";
    ctx.fillRect(10,10,50,50);
    
    var imgData=ctx.getImageData(30,30,50,50);
    ctx.rotate(30*Math.PI/180);
    ctx.putImageData(imgData,10,70);
    
    </script>
    
    </body>
    </html>
    Thank
    Nadav

  4. #4
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    It's because putImageData() simply does not specifically draw anything onto the canvas - it directly puts the image data (pixels) into the canvas just as they are. I don't believe you can rotate image data.

    One solution would be to redraw the part of the image you want to "copy" instead of using getImageData and putImageData. (In other words, you'd have to draw your red rectangle again in the new place after calling rotate().)

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles