javascript - 为网页编写动画标题的最有效方法是什么?

标签 javascript jquery canvas

我一直在尝试使用 Canvas 编写一个动画标题,其中随机添加图像(齿轮)和鼠标悬停事件,受影响的齿轮开始动画(转动)。我很难做到这一点。我真的在这上面浪费了很多时间并决定在这里寻求帮助。在这里使用 Canvas 是否可以,因为我读到单个 Canvas 对象没有“事件监听器”,因为 Canvas 框架被视为一个大对象。因此,让单个齿轮产生动画可能是“不可能”或效率不高...有什么好的教程可以解决这个问题,或者至少有一些我应该首先听到/阅读的技巧?

这是我的代码:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var cw=canvas.width;
var ch=canvas.height;

var imageURLs=[];  
imageURLs.push("https://image.freepik.com/free-icon/cogwheel_318-102625.png");
imageURLs.push("https://image.freepik.com/free-icon/cogwheel_318-102625.png");
imageURLs.push("https://image.freepik.com/free-icon/cogwheel_318-102625.png");
imageURLs.push("https://image.freepik.com/free-icon/cogwheel_318-102625.png");
imageURLs.push("https://image.freepik.com/free-icon/cogwheel_318-102625.png");
imageURLs.push("https://image.freepik.com/free-icon/cogwheel_318-102625.png");





//the loaded images will be placed in imgs[]
   var imgs=[];

   var imagesOK=0;
   loadAllImages(start);

   function loadAllImages(callback){
     for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
        imagesOK++; 
          if (imagesOK>=imageURLs.length ) {
             callback();
          }
    };
      img.onerror=function(){alert("image load failed");} 
    img.crossOrigin="anonymous";
    img.src = imageURLs[i];
  }      
}

function start(){

  // the imgs[] array now holds fully loaded images
  // the imgs[] are in the same order as imageURLs[]
  for(var i=0;i<imgs.length;i++){
    var randomX=Math.min(cw-imgs[i].width,Math.random()*cw);
    var randomY=Math.min(ch-imgs[i].height,Math.random()*ch);
    ctx.drawImage(imgs[i],randomX,randomY);
  }

}

最佳答案

这可能是您有兴趣查看的资源。它称为“GSAP”,代表“GreenSock 动画平台”。它允许使用 HTML5/JS 用很少的代码制作大量简单的动画。

它还提到了使用 Canvas 对象。特别是链接页面中间有一个部分显示了“staggerTo”效果,听起来与您想要做的类似。 (有一些盒子旋转并滚动到位)

我知道我最近一直在学习如何使用它,它的简单性给我留下了深刻的印象,他们的页面上确实有一些基本的入门教程以及 CodePen 链接。不管怎样,希望这能以某种形式或方式有所帮助。祝你好运!

http://greensock.com/tweenmax

关于javascript - 为网页编写动画标题的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36181879/

相关文章:

javascript - javascript 库的 .d.ts typescript 文件

javascript - DOM 元素返回未定义

php - 创建从上到下的无序列表而不是从左到右的最快方法

javascript - 使用JS逐渐褪色

javascript - 用于触摸屏的 HTML Canvas 帮助

javascript - 对动态图像内容使用媒体查询

javascript - 如何从异步调用返回响应?

javascript - 以编程方式使用 Angular JS 清空缓存和硬重置

javascript - 通过 JSON 树获取值然后打印到 console.log

javascript - 我正在尝试使用鼠标事件在 Canvas 上画一条线