0

I want to rotate an image IN javascript. The variable used for the image in javascript is heroImage. I am using jquery rotate, it works fine only when rotating images in html, but not in javascript. Normally it looks something like this

$("#image").rotate(angle);

But that only works for images created in html.

This is part of the code im currently using

var heroImage = new Image();
heroImage.src = "images/hero.png";

and its drawn of canvas , if that helps. the problem is #image can only refer to a html div element afaik.. The answer that im not looking for is this:

$("#image").rotate(angle);

Because that only works for html images

Its for a game, so everything has to be in javascript , anything css related doesnt seem to work. It also has to be IE9 compatible

none
  • 9
  • 2
  • 6

3 Answers3

1

You can draw it on canvas and then rotate scene in canvas

ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(Math.PI / 4);

or, rotate whole canvas using CSS3 transforms

document.getElementById('#canvas').style.webkitTransform = "rotate(45deg)";
Artek Wisniewski
  • 797
  • 5
  • 13
0

You can use CSS3 for this job.

img.rotated {
    transform: rotate(30deg);
}

As an example you can look into FontAwesome's CSS

http://fortawesome.github.io/Font-Awesome/examples/#rotated-flipped

If you have to use javascript, use can change CSS via JS.

document.getElementById('img.rotated').style.transform = rotate(30deg);
Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
0

Firstly add 'id' property to image

heroImage.id = 'image';

and add css for the 'image' as follows

$('#image').css('transform', 'rotate('+angle+'deg)');

here is detailed discussion on acheieving this

Community
  • 1
  • 1
Sreedhar M B
  • 179
  • 4
  • 15
  • Thats interesting, ill take a look at it. – none Aug 22 '13 at 10:18
  • javascript:heroImage.id = 'image'; heroImage.angle = 45; and I added the css like you said, but it doesnt seem to work – none Aug 22 '13 at 10:25
  • here it is. if write heroImage.id ='image'; heroImage.src='images/hero.png' it will be converted to since img doesnot have any valid attribute called angle it doesnot work. essential by adding css like following $('#image').css('transform', 'rotate(90deg)'); it appends to the as In this example value of angle is hardcoded. To make it dynamic use the code this $('#image').css('transform', 'rotate('+angle+'deg)'); where 'angle' is a variable. – Sreedhar M B Aug 23 '13 at 05:42