LoginSignup
30
21

More than 5 years have passed since last update.

《CreateJSとか》canvas要素の高解像度デバイスへの対応のしかた。

Last updated at Posted at 2017-03-02

「CreateJS」を利用しているときなど canvas要素に何か描画するとき、canvas要素はビットマップなので、Retinaディスプレイなどの高解像度ディスプレイだと、ボケて表示されてしまいます。

これに対応するのはとても簡単で、画像をRetina対応するときと同じような方法で実現することができます。
元の画像を大きくしておいて、style属性で縮めるやり方です。

JavaScriptで制御します。

コード


const canvas = document.getElementById('exCanvas');

canvas.width *= devicePixelRatio;
canvas.height *= devicePixelRatio;

canvas.style.width = String(canvas.width / devicePixelRatio) + "px";
canvas.style.height = String(canvas.height / devicePixelRatio) + "px";

解説

まず、取得したcanvas要素の幅と高さの、width属性とheight属性をdevicePixelRatio分だけ拡大します。


canvas.width *= devicePixelRatio;
canvas.height *= devicePixelRatio;

つぎに、canvas要素のstyle属性のwidthheightdevicePixelRatio分だけ縮小します。


canvas.style.width = String(canvas.width / devicePixelRatio) + "px";
canvas.style.height = String(canvas.height / devicePixelRatio) + "px";

これで高解像度対応することができました。

CreateJSのとき

if文で分岐しておきます。
stage.scaleXで伸縮するところがポイントかと思います。


const target = 'exCanvas',
      stage = new createjs.Stage(target),
      canvasW = 300,
      canvasH = 200;

stage.canvas.width = canvasW;
stage.canvas.height = canvasH;

if (window.devicePixelRatio) {
  const canvas = document.getElementById(target);
  canvas.width *= devicePixelRatio;
  canvas.height *= devicePixelRatio;
  canvas.style.width = String(canvas.width / devicePixelRatio) + "px";
  canvas.style.height = String(canvas.height / devicePixelRatio) + "px";
  stage.scaleX = stage.scaleY = window.devicePixelRatio;
}

おわります。

30
21
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
30
21