繁体   English   中英

如何将四个旋转图像添加到动画背景?

[英]How do I add four rotating images to an animated background?

我正在尝试将四个旋转图像添加到动画背景中。

我只能使用下面的代码使一张图像正常工作。

如何添加其他三个图像?

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);
}

这应该帮助你,我刚刚创建称为对象rotatingimage存储的位置,图像和当前旋转。 我们在“ setInterval”函数调用中调用“ draw”方法,该方法涉及旋转画布,然后正确绘制精灵。

只是旋转许多图像的注释会导致画布滞后,当CurrentRotation变量达到>359时也永远不会重置为0,因此CurrentRotation变量会越来越高,您可能需要在RotatingImage.prototype.Draw进行修复功能

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

Java脚本

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM