JavaScript 网页图标变成视频图标

看下图,仔细看↓

class VideoIcon {
  constructor(videoPath, iconSize = 32) {
    this.videoPath = videoPath;
    this.iconSize = iconSize;
    this.iconLink = null;
    this.video = null;
    this.canvas = null;
  }

  initVideo() {
    const video = document.createElement('video');
    video.crossOrigin = 'anonymous';
    video.controls = true;
    video.src = this.videoPath;
    video.width = 0;
    video.autoplay = true;
    video.style.display = 'none';
    this.video = video;
    document.body.appendChild(video);
  }

  bindVideoEvent() {
    const {video} = this;
    video.addEventListener('timeupdate', (e) => {
      this.videoToImage();
    })
  }

  initCanvas() {
    const canvas = document.createElement('canvas');
    canvas.width = this.iconSize;
    canvas.height = this.iconSize;
    this.canvas = canvas;
  }

  videoToImage() {
    const context = this.canvas.getContext('2d');
    const {iconSize, video} = this;
    context.clearRect(0, 0, iconSize, iconSize);
    context.drawImage(video, 0, 0, iconSize, iconSize);
    this.setFaviconIcon();
  }

  setFaviconIcon() {
    const url = this.canvas.toDataURL();
    this.iconLink.href = url;
  }

  getLinkIconTag() {
    const head = document.querySelector('head');
    const links = Array.from(head.querySelectorAll('link'));
    const [iconTag] = links.filter(item => item.rel === 'icon');
    if (iconTag) {
      this.iconLink = iconTag;
    } else {
      const link = document.createElement('link');
      link.rel = 'icon';
      this.iconLink = link;
      document.head.appendChild(link);
    }
  }

  init() {
    this.getLinkIconTag()
    this.initVideo()
    this.initCanvas()
    this.bindVideoEvent()
  }
}

demo

可以将上面的代码存入云端,然后为chrmoe新建一个书签,将书签的网址改为以下:

javascript:(function(){const script=document.createElement('script');script.id ='vIcon';script.src='https://cdn.jiajiwei.top/js/iconVideo.js';if(document.querySelector('#vIcon')){script=null;return null;}document.body.appendChild(script);script.onload=function(){const v=new VideoIcon('https://cdn.jiajiwei.top/video/watermelon.mp4').init();}})();

然后我们打开http网站的页面点击我们设置好的书签,图标就开始播放视频啦

posted @ 2020-12-11 10:02  demo_you  阅读(267)  评论(0编辑  收藏  举报