0

My goal is to make a canvas where I can easily change the scale and specify different degrees of rotation for an image. And also display it in the center of the canvas. However when I translate the canvas before I do that rotation, it doesn't center the object.

I'm fairly positive the problem lies in my calculation for the translate and drawImage but I'm not sure what the proper formula would be.

    var canvas = document.getElementById('myCanvas');
    var image = new Image();
    var dist;
    var imgScale = .5;
    var imgH, imgW;
    var cxt;
    image.src = 'http://t2.gstatic.com/images?q=tbn:ANd9GcQQveW9AJCxOC8Phnq3vptJIxPFHlxNw63q4pudc66dM4O96vtm';
    image.onload = function() {
      imgH = image.height * imgScale;
      imgW = image.width * imgScale;
      dist = Math.ceil(Math.pow((Math.pow(imgW, 2) + Math.pow(imgW, 2)), .5));
      canvas.width = dist;
      canvas.height = dist;
      cxt = canvas.getContext('2d');
      cxt.save();
      cxt.translate(canvas.width / 2 - imgW / 2, canvas.height / 2 - imgH / 2);
      cxt.drawImage(image, 0, 0, imgW, imgH);
      cxt.restore();
      //
      setTimeout(function() {

        cxt.save();

        //Suspect line
        cxt.translate(canvas.width / 2 - imgW / 2, canvas.height / 2 - imgH / 2);

        cxt.rotate(45 * Math.PI / 180);

        //Suspect line
        cxt.drawImage(image, 0, 0, imgW, imgH);
        cxt.restore();

      }, 1000);
    };
<canvas id="myCanvas" style="border: 1px solid black" />
Schwarz
  • 395
  • 4
  • 18
  • Your question is a duplicate of a previously answered Q&A, but here's how to fix your code: `ctx.drawImage( image, -imgW/2, -imgH/2 )`. – markE Apr 14 '16 at 18:45
  • @markE I tried it here but the two rotations I make still have it in the top left corner. http://jsfiddle.net/VPLZc/55/ – Schwarz Apr 14 '16 at 19:20
  • Check out the linked duplicate answer. It rotates the image from the canvas centerpoint and allows more than one rotation. – markE Apr 14 '16 at 20:11

0 Answers0