2016-12-17 15 views
1

アニメーションの背景に4つの回転イメージを追加しようとしています。4つの回転イメージをアニメーションの背景に追加するにはどうすればよいですか?

以下のコードで正しく動作する画像は1つしか取得できません。

他の3つの画像にどのように追加できますか?

var canvas = document.getElementById('c'); 
var ctx = canvas.getContext('2d'); 

var img = document.createElement('img'); 
img.onload = function(){ 
    render(); 
} 
img.src = 'nano3.png'; 

function drawImage(img,x,y,r,sx,sy){ 
    sx=sx||0; 
    sy=sy||0; 
    r=(r*Math.PI/180)||0; 
    var cr = Math.cos(r); 
    var sr = Math.sin(r); 
    ctx.setTransform(cr,sr,-sr,cr,x-(cr*sx-sr*sy),y-(sr*sx+cr*sy)); 
    ctx.drawImage(img,1,2); 
} 

var r = 1; 
function render(){ 
    requestAnimationFrame(render); 

    ctx.setTransform(1, 0, 0, 1, 0, 0); 
    ctx.clearRect(0,0,800,800); 

    drawImage(img,50,50,r++,img.width/2,img.height/2); 
} 

答えて

3

図面に変換を適用するために、保存を使用して復元することができ、私はただ、場所を格納rotatingimageとして知られているオブジェクトを作成しました画像とその現在の回転私たちはcanvasを回転させてスプライトを正しく描くことを扱う 'setInterval'関数呼び出しで 'draw'メソッドを呼び出します。

ただ多くの画像を回転するノートは、それはそう CurrentRotation変数は高く高く続けるだろう >359に達したときにキャンバスにも CurrentRotation変数が0にリセットされることは決してありません遅れることがあります、あなたは RotatingImage.prototype.Draw機能でそれを修正することもできます

jsFiddle:https://jsfiddle.net/xd8brfrk/

Javascriptを

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 

function RotatingImage(x, y, spriteUrl, rotationSpeed) { 
    this.XPos = x; 
    this.YPos = y; 
    this.Sprite = new Image(); 
    this.Sprite.src = spriteUrl; 
    this.RotationSpeed = rotationSpeed; 
    this.CurrentRotation = 0; 
} 

RotatingImage.prototype.Draw = function(ctx) { 
    ctx.save(); 
    this.CurrentRotation += 0.1; 
    ctx.translate(this.XPos + this.Sprite.width/2, this.YPos + this.Sprite.height/2); 
    ctx.rotate(this.CurrentRotation); 
    ctx.translate(-this.XPos - this.Sprite.width/2, -this.YPos - this.Sprite.height/2); 
    ctx.drawImage(this.Sprite, this.XPos, this.YPos); 
    ctx.restore(); 
} 

var RotatingImages = []; 

RotatingImages.push(new RotatingImage(50, 75, "http://static.tumblr.com/105a5af01fc60eb94ead3c9b342ae8dc/rv2cznl/Yd9oe4j3x/tumblr_static_e9ww0ckmmuoso0g4wo4okosgk.png", 1)); 

RotatingImages.push(new RotatingImage(270, 25, "http://static.tumblr.com/105a5af01fc60eb94ead3c9b342ae8dc/rv2cznl/Yd9oe4j3x/tumblr_static_e9ww0ckmmuoso0g4wo4okosgk.png", 1)); 

RotatingImages.push(new RotatingImage(190, 180, "http://static.tumblr.com/105a5af01fc60eb94ead3c9b342ae8dc/rv2cznl/Yd9oe4j3x/tumblr_static_e9ww0ckmmuoso0g4wo4okosgk.png", 1)); 

RotatingImages.push(new RotatingImage(100, 270, "http://static.tumblr.com/105a5af01fc60eb94ead3c9b342ae8dc/rv2cznl/Yd9oe4j3x/tumblr_static_e9ww0ckmmuoso0g4wo4okosgk.png", 1)); 

setInterval(function() { 
    ctx.fillStyle = "#000" 
    ctx.fillRect(0, 0, canvas.width, canvas.height); 

    for (var i = 0; i < RotatingImage.length; i++) { 
    var rotatingImage = RotatingImages[i]; 
    rotatingImage.Draw(ctx); 
    } 
}, (1000/60)); 
関連する問題