什么's是为网页编写动画标题的最有效方法

What's the most efficient way of coding an animated header for a webpage?

本文关键字:标题 动画 方法 有效 网页 什么      更新时间:2023-09-26

我一直在尝试用画布编写一个动画标题,其中随机添加图像(齿轮)并添加鼠标悬停事件,受影响的齿轮开始动画化(转动)。我很难做到这一点。我真的在这上面浪费了很多时间,决定在这里寻求帮助。在这里使用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用很少的代码制作许多简单的动画。

它还提到了使用画布对象。特别是在链接的页面中间有一个部分显示了一个"staggerTo"效果,听起来与你想要做的类似

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

http://greensock.com/tweenmax