LoginSignup
3
4

More than 5 years have passed since last update.

Live2Dで縦横の比率を調整する

Last updated at Posted at 2017-03-25

Live2DでCanvasの縦横サイズが異なる場合、以下のように伸びて描画されます。
(SampleApp1のサンプル以外)
def_canvas.png

それを回避する方法をメモしておきます。

開発環境

Live2D WebGL SDK2.1のSimpleサンプルをカスタム

ソースコード

まずはHTML部分にLive2DFramework.jsを追加します。この中に含まれるL2DMatrix44クラスを使います。

simple.htmlの12行目あたり
<!-- Live2D Library -->
<script src="../../lib/live2d.min.js"></script>
<script src="../../framework/Live2DFramework.js"></script>
<!-- User's Script -->
<script src="src/Simple.js"></script>

Live2DFramework.jsに比率調整用の以下コードを追加します。

Live2DFramework.jsの860行目あたり
L2DModelMatrix.prototype.setScale = function(width, height, scale)
{
    var scaleX = scale / width;
    var scaleY = -scale / height;
    this.scale(scaleX, scaleY);
}

Simple.draw()部分の行列部分を以下のように修正します。
canvasはグローバル変数にして、参照できるようにしておいて下さい。

Simple.jsの150行目あたり
//    // 表示位置を指定するための行列を定義する
//    var s = 2.0 / live2DModel.getCanvasWidth(); //canvasの横幅を-1..1区間に収める
//    var matrix4x4 = [
//        s, 0, 0, 0,
//        0,-s, 0, 0,
//        0, 0, 1, 0,
//       -1, 1, 0, 1
//        ];
//    live2DModel.setMatrix(matrix4x4);

// 描画してるLive2Dモデルのサイズを取得
var height = live2DModel.getCanvasHeight();
var width  = live2DModel.getCanvasWidth();
// Canvasのサイズ取得
var can_height = canvas.height;
var can_width  = canvas.width;

// Live2D用の行列定義
var mmat = new L2DModelMatrix(width, height);
// スケールを調整する関数に渡す
mmat.setScale(can_width, can_height, 0.7);
// ポジション(X, Y)
mmat.setCenterPosition(0.0, -0.5);
// 配列をセット
live2DModel.setMatrix(mmat.getArray());

これでCanvasサイズを変更しても縦横比率が正しくなりました!
custom_canvas.png

参考

Live2Dで位置とサイズを調整する

3
4
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
3
4