Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw multiple image's on canvas with each image rotated

I'm new into HTML5 programming and I wanted to know how to rotate each image when it is added into canvas. Should each of them be placed into a canvas and then rotated? If so how can i add multiple canvas into a single canvas context.

Fiddle : http://jsfiddle.net/G7ehG/

Code

function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        // get num of sources
        for(var src in sources) {
          numImages++;
        }
        for(var src in sources) {
          images[src] = new Image();
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images);
            }
          };
          images[src].src = sources[src];
        }
      }
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var sources = {
        image1: 'http://farm3.static.flickr.com/2666/3686946460_0acfa289fa_m.jpg',
        image2: 'http://farm4.static.flickr.com/3611/3686140905_cbf9824a49_m.jpg'
      };

      loadImages(sources, function(images) {
        context.drawImage(images.image1, 100, 30, 200, 137);
        context.drawImage(images.image2, 350, 55, 93, 104);
      });
like image 451
user1184100 Avatar asked Mar 22 '23 21:03

user1184100


1 Answers

In your comment you mentioned that you know about context.rotate, but you don't want the context to stay rotated. That's not a problem at all. First, calling context.rotate only affects things which are drawn afterwards. Anything drawn before will stay were it was. Second, it can be easily reversed after drawing.

  1. use context.save() to create a snapshot of all current context settings, including current rotation.
  2. use context.rotate(angle) and draw your image. The angle is in Radian. That means a full 360° circle is Math.PI * 2. The point the image will be is rotated around is the current origin of the canvas (0:0). When you want to rotate the image around its center, use context.translate(x, y) to set the origin to where you want the center of the image to be, then rotate, and then draw the image at the coordinates -img.width/ 2, -img.height / 2
  3. use context.restore() to return to your snapshot. Rotation and translation will now be like they were before.

Here is an example function which draws an image rotated by 45° at the coordinates 100,100:

function drawRotated(image, context) {
    context.save();
    context.translate(100, 100);
    context.rotate(Math.PI / 4);
    context.drawImage(image, -image.width / 2, -image.height / 2);
    context.restore();
}
like image 139
Philipp Avatar answered Mar 29 '23 22:03

Philipp