Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                .drop-zone

h1.title.is-3 Generate speed dial thumbnail for Vivaldi


//- TODO ドラッグ&ドロップ or ファイル選択
//- TODO 画像をまとめて処理したい

#app
  //- ブラウザ非対応の注釈
  p.has-text-danger(v-show="isSupportBrowser === false") お使いのブラウザは対応していません。
  
  //- アップロード
  .content
    .upload
      form()
        label.select-file
          input.file(type="file", accept="image/*")
          .button(:class="{ 'is-primary' : status.isDone === false }")
            span.icon
              i.fas.fa-file-upload
            span Choice a icon file
      span.has-text-grey-light or
      span Drag icon file here
    
    //- ドラッグでアップロード
    .drop-zone.is-overlay(:class="{ 'is-active': status.isDragOver === true }")
      p.is-size-4.has-text-white Upload
      
    //- ファイルのエラー
    p.help.is-danger(v-show="status.isUploaded && status.isImage === false") Only JPG, PNG, GIF, BMP and WEBP images are supported.
          
  //- 結果
  .result.content
    .item.is-inline-block

      canvas.preview(width="440", height="360")
      
      .name.is-size-7(v-show="uploaded.name !== ''") {{ uploaded.name }}

      //- アクション
      .action
        a.button(:href="download.png.src", :class="{ 'is-primary': status.isDone === true }" :download="download.png.name", :disabled="download.png.src === null")
          span.icon
            i.fas.fa-file-download
          span Download
              
            
!

CSS

              
                html {
  background-color: #f5f5f5;
}

body {
  padding: 20px;
}

canvas {
  vertical-align: top;  // 下のマージンを削除
}

.item {
  width: 440px;
}

.upload {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
  
  input[type="file"] {
    cursor: pointer;
  }
  
  > * {
    &:not(last-child) {
      margin-right: 1rem;
    }
  }
}

// ドラッグでアップロードするエリア
.drop-zone {
  display: none;
  
  &.is-active {
    display: flex;
    align-items: center;
    justify-content: center;
    border: solid 5px rgba(#1e88e5, 0.9);
    background-color: rgba(#1e88e5, 0.8);
    z-index: 100;
  }
}




// ファイル選択のボタン
.select-file {
  overflow: hidden;
  
  input[type="file"] {
    display: none;
  }
}

.preview {
  width: 440px;
  height: 360px;
  box-shadow: 2px 2px 5px 0 rgba(0, 0, 0, 0.2);
  margin-bottom: 0.25rem;
}

.name {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.action {
  margin-top: 0.75rem;
}

.button.is-text {
  text-decoration: none;
}
              
            
!

JS

              
                type Size = { width: number, height: number };  // サイズ

// ロゴの最大サイズ
const destSize: Size = {
  width: 300,
  height: 200
};

// 許容するファイルタイプ
const allowFileTypes = [
  { type: 'image/jpeg', ext: ['jpeg', 'jpg'] },
  { type: 'image/png', ext: ['png'] },
  { type: 'image/gif', ext: ['gif'] },
  { type: 'image/bmp', ext: ['bmp'] },
  { type: 'image/webp', ext: ['webp'] }
];


/**
 * 指定サイズに縮小
 *
 * @param 
 * @return
 */
function resize (from: Size): Size {
  let result;
  
  if (from.width >= destSize.width || from.height >= destSize.height) {
    // 縦横比を維持して縮小
    if (from.width / destSize.width >= from.height / destSize.height) {
      result = {
        width: destSize.width,
        height: Math.round(destSize.width / from.width * from.height)
      };
    }
    else {
      result = {
        width: Math.round(destSize.height / from.height * from.width),
        height: destSize.height
      };
    }
  }
  else {
    // 画像のサイズが足りないので、リサイズせずにそのまま返す
    result = from;
  }
  
  return result;
}


// Vueもcomponentになる

new Vue({
  el: '#app',
  data: {
    status: {
      isDragOver: false,  // ファイルをドラッグでアップロードしようとしているか
      isUploaded: false,  // アップロードされたか
      isImage: false, // 画像ファイルか
      isLoadError: false, // 画像の読み込みに失敗した
      isDone: false  // サムネイルが作成できた
    },
    uploaded: {
      file: null, // アップロードされたファイル
      name: ''  // ファイル名
    },
    file: '', // アップロードされた素材
    fileName: '', // 
    isSupportBrowser: Modernizr.canvas && Modernizr.filereader, // サポート環境ではない
    element: {
      fileInput: null,  // ファイルアップロードのinput
      dropzone: null, // ドラッグでアップロードするエリア
      canvas: null, // 完成した画像を表示するcanvas
      context2d: null // ↑のcanvas context
    },
    download: {
      png: {
        src: null,
        name: ''
      },
      jpg: {
        src: null,
        name: ''
      }
    }
  },
  
  mounted () {
    if (Modernizr.canvas) {
      this.element.canvas = this.$el.querySelector('canvas.preview');
      this.element.context2d = this.element.canvas.getContext('2d');

      // input fileでファイルをアップロード
      const $file = this.$el.querySelector('.file'); // アップロード用input
      this.element.fileInput = $file;

      $file.addEventListener('change', this.onUploadByInput);
      
      
      // ドラッグ&ドロップでファイルをアップロード
      const $dropZone = this.$el.querySelector('.drop-zone'); // ドラッグでアップロード用
      this.element.dropzone = $dropZone;
      
      window.addEventListener('dragenter', () => {
        this.status.isDragOver = true;
      });
      
      $dropZone.addEventListener('dragenter', this.allowDrag);
      $dropZone.addEventListener('dragover', this.allowDrag);
      $dropZone.addEventListener('dragleave', (e: Event) => {
        this.status.isDragOver = false;
      });
      
      // ファイルを受け付ける
      $dropZone.addEventListener('drop', this.onUploadByDrop);
    }
  },
  
  methods: {
    
    /**
     * input fileからアップロードされた
     *
     */
    onUploadByInput (e: Evnet) {
      this.onUploaded(this.element.fileInput.files[0]);
    },
    
    /**
     * ドラッグ&ドロップでファイルがアップロードされた
     *
     */
    onUploadByDrop (e: Event) {
      e.preventDefault();
      
      this.status.isDragOver = false;
      
      const files = e.dataTransfer.files; // ファイル
      if (files.length > 0) {
        this.onUploaded(files[0]);
      }
    },
    
    /**
     * ファイルが選択された
     *
     * @param file
     */
    onUploaded (file) {
      // TODO 複数ファイルに対応したい
            
      // ステータスをリセットする
      this.resetStatus();
      this.status.isUploaded = true;
      
      // ダウンロードのリンクをリセットする
      this.resetDownloadLink();
      
      // ドラッグのアップロードをリセットする
      this.status.isDragOver = false;
      
      // canvasをクリアする
      this.element.context2d.clearRect(0, 0, this.element.canvas.width, this.element.canvas.height);
      
      if (_.includes(_.map(allowFileTypes, 'type'), file.type)) {
        // 許容するファイル形式なら処理を続ける
        this.status.isImage = true;
        this.uploaded = {
          file,
          name: file.name
        }
      }
      else {
        // 許可されたファイルフォーマットではない
        this.status.isImage = false;
        this.uploaded = {
          file: null,
          name: ''
        };
      }
    },
    
    /**
     * ファイルが変更された
     *
     */
    onFileChanged (file: File) {
      
      // blueimp-load-imageで、exif orientationを解決しつつ画像を読み込む
      const loadingImage = loadImage(file, (image: Image) => {
        this.draw(image);
      });
      
      loadingImage.addEventListener('error', () => {
        this.status.isLoadError = true;
      });
    },
    
    /**
     * ファイルのドラッグを許容する
     *
     */
    allowDrag (e: Evnet) {
      // コレがないとドラッグでファイルを表示してしまう
      e.dataTransfer.dropEffect = 'copy';
      e.preventDefault();
    },
    
    /**
     * canvasに描画する
     *
     * @param image
     */
    draw (image: Image) {
      const resizer = new pica(); // picaのインスタンス
      
      // 調整したサイズ
      const size = resize({
        width: image.width,
        height: image.height
      });
      
      // picaのリサイズ用のキャンバスを生成
      const tmp = document.createElement('canvas');
      tmp.width = size.width;
      tmp.height = size.height;
      
      // document.body.appendChild(tmp); // TEST
      
      resizer.resize(image, tmp, {
        alpha: true
      })
        .then((canvas) => {
          //----------------------------------
          // 画像をcanvasに表示
          //----------------------------------
        
          // プレビュー用canvasにコピー
          // picaの出力先にcanvasを指定する必要があるため
          const image = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
        
          // 表示用のcanvasにコピー(中央に)
          this.element.context2d.putImageData(image, Math.round((this.element.canvas.width - size.width) / 2), Math.round((this.element.canvas.height - size.height) / 2));
        
          
          //----------------------------------
          //  ダウンロード用のリンクを生成
          //----------------------------------
          const ext = new RegExp(`\.(${_.flatten(_.map(allowFileTypes, 'ext')).join('|')})$`, 'i'); // アップロード可な拡張子の正規表現
          const fileName = this.uploaded.name.replace(ext, '');  // 拡張子を削除したファイル名

          this.download.png = {
            src: this.element.canvas.toDataURL('image/png'),
            name: `${fileName}.png`
          };
          this.download.jpg = {
            src: this.element.canvas.toDataURL('image/jpeg'),
            name: `${fileName}.jpg`
          };
        
          this.status.isDone = true;
        });
    },
    
    /**
     * ステータスをリセットする
     *
     */
    resetStatus () {
      this.status.isUploaded = false;
      this.status.isImage = false;
      this.status.isLoadError = false;
      this.status.isDone = false;
    },
    
    /**
     * ダウンロードリンクをリセットする
     *
     */
    resetDownloadLink () {
      this.download.png = {
        src: null,
        name: ''
      };
      this.download.jpg = {
        src: null,
        name: ''
      };
    }
    
  },
  
  watch: {
    'uploaded.file': function (newFile) {
        this.onFileChanged(newFile);
    }
  }
});
              
            
!
999px

Console