Ad

Unable To Rotate Canvas In Canvas

- 1 answer

I've created main canvas, canvas_panorama and canvas_image:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.id = 'canvas_parent';
canvas.width = 600; canvas.height = 300;
document.body.appendChild( canvas );

var canvas_panorama = document.createElement("canvas");
var canvas_panorama_ctx = canvas_panorama.getContext("2d");
canvas_panorama.height= 300; canvas_panorama.width= 600;

var canvas_image = document.createElement("canvas");
var canvas_image_ctx = canvas_image.getContext("2d");
canvas_image.height= 150; canvas_image.width= 150;

and function to draw stuff into canvas:

 function redraw(){  
        canvas_image_ctx.drawImage(image_img, 0, 0, 150, 150);
        canvas_panorama_ctx.drawImage(panorama_img, 0, 0, 600, 300);
        canvas_panorama_ctx.drawImage(canvas_image, 20, 20);
        ctx.drawImage(canvas_panorama, 0, 0);
        canvas_image_ctx.rotate(angle);
  }
  redraw();

Then I'm checking if canvas is right clcked and calling function to get new angle:

function getAngle( e, pw ){
      var offset = pw.offset();
      var center_x = (offset.left) + ($(pw).width() / 2);
      var center_y = (offset.top) + ($(pw).height() / 2);
      var mouse_x = e.pageX;
      var mouse_y = e.pageY;
      var radians = Math.atan2(mouse_x - center_x, mousetan2(mouse_x - center_x, mouse_y - center_y);
      angle = (radians * (180 / Math.PI) * -1) + 180;
}

But I'm not able to rotate it, I need to keep images in special canvas becouse next behind me is dragging it.
Don't you have any idea what am I doing wrong?
FIDDLE with example.

Ad

Answer

  • clickAngle is undefined and throwing an error preventing the getAngle function to be called. You have to define it befor you can use it
  • Typo agetAngle should be getAngle in the mouse event where you call it.
  • Then the getAngle function has radians but you convert to degrees then call redraw using angle (in degrees) rather than radians. ALL javascript API's use radians not degrees..

That got it rotating the canvas.. PS it is always hard to see where typos are when you have messy code. You will save yourself endless hassles by making sure your code is always neat.

Also Dev tools helps you trace these types of bugs. Hit F12 on your browser for the programmer's best friend. In code use console.log("this goes to console") to see what your code is doing and list variable to the console.

Ad
source: stackoverflow.com
Ad