Javascript:水平翻转图像对象并将其保存到新的图像对象中

时间:2014-02-06 17:50:26

标签: javascript sprite

我创建了一个显示在画布元素上的箭头精灵,最初它指向右侧并向右移动。当它开始向左移动时我想旋转这个精灵。

我使用多个精灵,所以翻转整个画布并不是一个真正的选择。

我当然可以创建两个单独的精灵,但理想情况下我认为如果我在开始时旋转精灵并将其保存到新的Image对象中会更好。这可能吗?我应该怎么做?

P.S。仅限Javascript,没有jQuery。

var imagetest = new Image();
imagetest.src = "./img/arrow.png";

1 个答案:

答案 0 :(得分:5)

您可以将目标设置为现有IMG标记或某些JS Image对象:

<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>