2022.10.18

93 阅读1分钟

1.纯前端实现图片下载

图片路径为 http://ip:端口/.../test.png 时候,使用a标签或者location.href,window.open都会跳到一个新的图片网页,可以使用以下方法:

downloadByBlob(url,name) {
    let image = new Image()
    image.setAttribute('crossOrigin', 'anonymous')
    image.src = url
    image.onload = () => {
      let canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      let ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0, image.width, image.height)
      canvas.toBlob((blob) => {
        let url = URL.createObjectURL(blob)
        download(url,name)
        // 用完释放URL对象
        URL.revokeObjectURL(url)
      })
    }
  },
  function download(href, name) {
  let eleLink = document.createElement('a')
  eleLink.download = name
  eleLink.href = href
  eleLink.click()
  eleLink.remove()
}

2.vue中动态显示时间

data() {
    return {
//时间1定义
      timer: undefined,
      nowTime: new Date(),
    };
  },
created() {
//时间1方法
// 要显示时间,在渲染页面之前一直调用该函数,对this.time进行赋值开启定时
this.timer = setInterval(() => { 
this.nowTime = new Date().toLocaleString();
}); 
},
// 关闭页面销毁定时器
beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
//时间2方法  
  FormatTime() {
      //设置返回显示的日期时间格式
      var date = new Date();
      var year = this.formatTime(date.getFullYear());
      var month = this.formatTime(date.getMonth() + 1);
      var day = this.formatTime(date.getDate());
      var hour = this.formatTime(date.getHours());
      var minute = this.formatTime(date.getMinutes());
      var second = this.formatTime(date.getSeconds());
      var weekday = date.getDay();
      var weeks = new Array(
        "星期日",
        "星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六"
      );
      var week = weeks[weekday];
        //这里设置你要显示的格式
      return `${year}年-${month}月-${day}${hour}:${minute}:${second} ${week}`;
    },
    formatTime(n) {
      //判断时间是否需要加0
      if (n < 10) {
        return "0" + n;
      } else {
        return n;
      }
    },

使用直接在页面中你需要的部分加上:   时间1:  {{nowTime}}   时间2:  {{this.FormatTime()}}