「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
属性のwidth
とheight
をdevicePixelRatio
分だけ縮小します。
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;
}
おわります。