1

I am working on a program in Javascript while I tried to rotate my image I have drawn. I tried to search on google to find my answer but all I got was how to rotate the whole canvas. What I am searching for is a way to rotate just an image (think like this. I want to rotate a warrior dependent on the direction he is walking in). I tried many different codes but all went to the same, rotate the whole canvas.

Here is an example of what I used:

ctx.rotate(20*Math.PI/180); 

and also:

var angle = 0; //init angle
images[0].onload = function () {
    ctx.drawImage(images[0], 0, 0);
    setInterval(function () {
        ctx.save();
        ctx.clearRect(-ctx.canvas.width / 2, -ctx.canvas.height / 2, ctx.canvas.width, ctx.canvas.height);
        ctx.rotate(Math.PI / 180 * (angle += 10)); //rotating at 10 degrees interval..
        ctx.drawImage(images[0], 0, 0);
        ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2);
        ctx.restore();
    }, 16);
}

please help me out

5
  • 1
    Try this jQuery plugin , yet great examples : code.google.com/p/jqueryrotate/wiki/Examples Commented Apr 27, 2013 at 14:30
  • The problem is i will get a new problem. How do i call a function in a JQuery file from a JavaScript file? Commented Apr 27, 2013 at 14:36
  • 1
    Like this call js to jq object-> stackoverflow.com/questions/9489779/… ,for exp: var jsObj=document.getElementByTageName("title");var jqObj=$(jsObj).html();$(jsObj).html("jQuery Test"); Commented Apr 27, 2013 at 14:38
  • The code seems fine, saving and restoring the context should allow you to rotate just the image. Everything drawn before and after shouldn't be affected. Can you setup a jsfiddle? Commented Apr 27, 2013 at 14:48
  • here is the "game" right now: berzanlabb.se/te11e/robrot060/JavaScript/index.html Commented Apr 27, 2013 at 14:53

1 Answer 1

0

The rotating of the canvas is part of how to create the rotation relative to the image.
To keep the image's visible position the same and not move it, you have to center it first.
Without centering the image you will only acheive the visual effect of rotating the entire canvas.
You have to throw in a bit of math to get it to rotate around the center of the image.

ctx.save();
ctx.translate(x, y); /*X and Y of the image, center point of the image */
ctx.rotate((Math.PI / 180) * rotation); /*rotation is in degrees, so this converts it to rads */
ctx.drawImage(img, -(img.width/2), -(img.height/2)); /* Draw and center the image */
ctx.restore();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.