0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScript(jQuery)で画像をリサイズする方法(JS以外でも可)

Posted at

#画像をリサイズするJS以外でも使用可

画像をクリックしたら画像の縦横比を維持した状態で指定のサイズに画像をリサイズする


$('img')on.('click', function(){
  //画像のsrcを取得
  let src = $(this).attr('src');

  let width = 400;//任意の数値
  let height = 400;//任意の数値

  //元の画像サイズ
  let originalWidth = $(this).width();
  let originalHeight = $(this).height();

  //割合計算(小数点が出る場合はコンソールで注意が出る場合も。その場合はMath.ceil()などを使用して切り上げる)
  let rate = originalWidth / originalHeight;
  height = (width / rate);
  if(rate < 1){
    height = width;
    width = width * rate;
  }
  //リサイズした画像をwidth、heightともに追加
  $('body').append(`<div><img src="${src}" width="${width}" height="${height}"></div>`);
  
});

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?