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

              
                <div id="canvas-container">
  <canvas id="canvas"></canvas>
</div>
              
            
!

CSS

              
                #canvas-container {
/*  ここの%を変更すると比率を保った状態でリサイズ  */
  max-width: 50%;
  margin: 0 auto;
}
#canvas {
  vertical-align: bottom;
  width: 100%;
}

              
            
!

JS

              
                const parent = document.getElementById("canvas-container");
const canvas = document.getElementById("canvas");
// 2次元の描画を行うメソッド
const ctx = canvas.getContext("2d");
// リサイズ時の判定用変数
let isInit = false;
// img要素を生成
const img = new Image();
// 読み込み用の画像をimg要素に挿入
img.src = "https://source.unsplash.com/xGy_DKmPYEk/";
// img.src = "https://picsum.photos/seed/picsum/460/460";

let render = () => {
  let scale = 0;
  console.log(isInit);
  if (isInit) {
    // リサイズ時の処理
    // canvasを再描画するために既存のものを消す
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  } else {
    // リサイズ前の一度目の処理
    // 一度目以外はtrue判定になる
    isInit = true;
  }
  // 画像の元のサイズ取得
  let img_w = img.naturalWidth;
  let img_h = img.naturalHeight;
  // 親の幅を取得
  let parent_w = parent.clientWidth;
  // 親の幅をcanvas当てる
  canvas.width = parent_w;
  // 横幅の比率から高さを割り出す
  canvas.height = img_h * (parent_w / img_w);
  // 比率を求める
  scale = canvas.width / img.width;
  ctx.setTransform(scale, 0, 0, scale, 0, 0);
  // canvasに描画
  ctx.drawImage(img, 0, 0);
};

let main = () => {
  img.addEventListener("load", render, false);
  window.addEventListener("resize", render, false);
};
main();

              
            
!
999px

Console