I've created an arrow sprite displayed on a canvas element, initially it points to the right and it moves to the right. When it starts moving to the left I want to rotate this sprite.
Im using multiple sprites so flipping the entire canvas is not really an option.
I could of course create two seperate sprites, but ideally I think it would be better if I rotate the sprite at the start and save it into a new Image object. is this possible? and how should I do this?
P.S. Javascript only, no jQuery.
var imagetest = new Image();
imagetest.src = "./img/arrow.png";
I've created an arrow sprite displayed on a canvas element, initially it points to the right and it moves to the right. When it starts moving to the left I want to rotate this sprite.
Im using multiple sprites so flipping the entire canvas is not really an option.
I could of course create two seperate sprites, but ideally I think it would be better if I rotate the sprite at the start and save it into a new Image object. is this possible? and how should I do this?
P.S. Javascript only, no jQuery.
var imagetest = new Image();
imagetest.src = "./img/arrow.png";
Share
Improve this question
edited Feb 6, 2014 at 17:56
inControl
asked Feb 6, 2014 at 17:50
inControlinControl
2,3444 gold badges25 silver badges40 bronze badges
2
- Can't you just create a new image object with the same URL and apply a CSS3 transform to it to flip it? – jfriend00 Commented Feb 6, 2014 at 17:53
- The thing is i'm creating an image object using javascript, it won't be placed in the DOM tree. – inControl Commented Feb 6, 2014 at 17:54
1 Answer
Reset to default 7You can set the target either to an existing IMG tag or some JS Image object :
<html>
<head>
<script>
function flip(src,target){
var img = new Image();
img.onload = function(){
var c = document.createElement('canvas');
c.width = this.width;
c.height = this.height;
var ctx = c.getContext('2d');
ctx.scale(-1,1);
ctx.drawImage(this,-this.width,0);
this.onload = undefined;
target.src = c.toDataURL();
}
img.src = src;
}
</script>
</head>
<body onload="flip('SOMESPRITE.PNG',document.getElementById('fliptest'));">
<img id="fliptest" />
</body>
</html>