最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

sprite - Javascript: Horizontally flip an image object and save it into a new image object - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7

You 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>
发布评论

评论列表(0)

  1. 暂无评论