美文网首页
Angular5 图片下载指令(Directive)

Angular5 图片下载指令(Directive)

作者: niccky | 来源:发表于2018-09-21 15:12 被阅读0次
    import { Directive, Input, HostListener } from '@angular/core';
    
    @Directive({
      selector: '[imageToLocal]',
    })
    export class ImageToLocalDirective {
      @Input() name: string = 'code.png';
      @Input() path: string = '';
    
      @HostListener('click')
      onClick() {
        if (!this.path) return;
        this.downloadImg(this.path, this.name);
      }
    
      downloadImg(path, name = 'code.png'): void {
        const image = new Image();
        image.setAttribute('crossOrigin', 'anonymous');
        image.onload = function() {
          const canvas = document.createElement('canvas');
          canvas.width = image.width;
          canvas.height = image.height;
          const context = canvas.getContext('2d');
          context.drawImage(image, 0, 0, image.width, image.height);
          const url = canvas.toDataURL('image/png');
          const a = document.createElement('a');
          const event = document.createEvent('MouseEvents');
          event.initMouseEvent(
            'click',
            true,
            false,
            window,
            0,
            0,
            0,
            0,
            0,
            false,
            false,
            false,
            false,
            0,
            null,
          );
          a.download = name;
          a.href = url;
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(canvas.msToBlob(), name);
          } else {
            a.dispatchEvent(event);
          }
        };
        image.src = path + '?v=' + new Date().getTime();
      }
    }
    
    

    使用指令

    ...
    const imgInfo = {
      path:"/path/img/xxx.png",
      name:"code.png"
    }
    ...
     <a imageToLocal [name]="imgInfo.name" [path]="imgInfo.path">下载</a>
    

    相关文章

      网友评论

          本文标题:Angular5 图片下载指令(Directive)

          本文链接:https://www.haomeiwen.com/subject/proanftx.html