LoginSignup
2
0

More than 1 year has passed since last update.

Canvasを画像化する

Posted at

はじめに

Canvasで作成したイメージは、そのままだとスマホで画像保存できません。
したがって、一度画像に変換して上げる必要があります。

以前記事で紹介したWebサービスをアップデートする際に実装しました。

コード

基本的な流れはimgタグに対して、src属性としてBase64に変換したCanvasを食わせる形です。

HTML

<img id="canvas">

Javascript

document.querySelector('#selectPeopleImg').addEventListener('change', (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  const reader = new FileReader()
  reader.onload = (event) => {
    imgData = event.target.result

    const img = new Image();
    img.onload = () => {
      const orgWidth  = img.width;  // 元の横幅を保存
      const orgHeight = img.height; // 元の高さを保存
      const newWidth = 300;  // 横幅を300pxにリサイズ
      const newHeight = orgHeight * (newWidth / orgWidth); // 高さを横幅の変化割合に合わせる
      //画像オブジェクトを生成
      const canvas = document.createElement('canvas');
      canvas.width = newWidth;
      canvas.height = newHeight;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, newWidth, newHeight);
      document.querySelector('#canvas').src = canvas.toDataURL()
    }
    img.src = imgData;
  }
  reader.readAsDataURL(file)
})
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0