VexFlow 打楽器譜

提供:yonewiki

VexFlow 使い方に戻る。

概要

 この記事はうまく表示されていないときは、試しにスーパーリロードをすることをお勧めします。もともと間違えていて、なんらかわらない場合もありえますが…。ブラウザによってやり方が違いますが、Chromeは再読み込みがスーパーリロードするようになっています。edgeはCtrlキーを押しながら更新ボタンを押すといいです。Safariはややこしいです。


 ここでは一本線に打楽器譜を記載するものと、ドラムセット譜でよく使われる変則的な符頭の表示について考えたいと思います。一線譜を引くのは簡単なのですが、ドラム独特のシンバル、ハイハット(オープンクローズ)、ペダルハイハットの記号がシンコーミュージックのようなフォントが無いですね。これは奥の手の奥の手がついに必要になってきてる予感です。2Voiceの管理が面倒な時は、架空の小節でも用意して、完全にわければいいのですね。奥の手の奥の手を使うにしても、さすがに面倒すぎて、一旦、記事の更新スピードが急ブレーキですね。自作の楽譜フォントは以前に作ったとは言え、Webフォント化はしてないっすからね。そこからだな。


 タブ譜も納得いってない部分が多いので、また、更にしんどいっすね。残りの記事はあと少しかなと思ってたんですけど、あせらずゆっくり考えましょうか。管理人、長考に入ります。


 ドラムセットで登場しえる記号を自作フォントに追加してみました。まだ配布できるレベルになっていないので、みなさんに紹介できるまでには時間がかかると思いますが、一応、暫定的に作ったフォントでは以下のようになりますっていう紹介はできそうな段階になりました。五線譜の一番下の線と一つ上線のとの間の音をヘ音記号なので、A/4と呼ぶならば、A/4がバスドラ、C/5がバスタム、E/5がスネア、G/5がタムです。ひし形はシンバル、xはハイハットで(oがついていればオープンハイハット、+がついていればクローズハイハットを意味します。)、F/5のxはハイハットはハイハットでもペダルハイハットを意味します。ハーフハイハットを半円でしめす場合もあれば、範囲指定で示す場合もありそうです。管理人は打楽器をたしなんでいないので、事情があまり詳しくないので、もっといろんな記号があったほうがいい可能性もありますね。でも、これで打楽器譜は大体カバーしたことになるかな。あとはパーカッション譜が描けるようになれば、網羅したことになるんでしょう。


 ドラムセットのハイハットのxしか想定していなかったので旗の向きが上向きのときしか想定していませんでした。下向きのxマークのフォントもいるんだな。もうちょっとフォント改造しないとな。ギタータブ譜も網羅してから配布するつもりなんで、先が長いですが、フォントが配布される時を楽しみにまっていて下さい。え?別に楽しみじゃない?そっすよね。結局、ここの管理人の好みでしかないフォントだからな。


 216行目までが、描画の記述を簡素化するための自作あるいはVexFlow公式が提案している関数になってしまいましたが、手軽に自作フォントを使うことができるようになっています。処理のイメージとしては、符旗を描画する処理はVexFlowにやってもらって、消したい符頭を持つNoteにあるNoteHead要素を消す処理を入れ込んでいます。完全に消すとあとあと困るかもしれないので透明にしておきました。印刷するときに困らなければいいのですが…。心配です。それで、消したところの座標にあらたな符頭をつけるみたいな処理を行っています。今回思いついたこの方法は次あたりの記事になるタブ譜の記述でも自分が考えたフォントを使う場合にも便利な方法かなと感じています。まぁなかなか強引なことをやってはいますね。addShift関数は小節のノート群を指定するとその座標を取得するという処理を担っています。これをinsertTextToSVGの引数のオブジェクトに設定してやると一気に書き換えたい収集したポジションにたいして描画ができるという作戦です。これくらいの苦労ならばVexFlowの記述量とそん色ないほどの作業量だなと感じるレベルで、メンドクサイ処理が可能となります。


 関数を使わないで描画しようとするとコード量は一小節あたり400行は必要でしたが、20行くらいにまで減ったと思います。16ビートの曲の楽譜なんかは書きたくないって思ってしまうところをなんとかした感じです。強引な関数なので使い方が難しいっすね。読み解くのに時間がかかりそうなギミックになっています。なるはやで解説記事を作成しないと駄目だなとは思っています。

 

打楽器譜


 コードは以下のとおりです。


<div id="yonet202403Mid_Output01"></div>
<script>
///////////////////////
(function(){
class Position {
  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }
}
var VF = Vex.Flow;
const Instrument1 = new Position();
const Instrument2 = new Position();
const Instrument13 = new Position();
const Instrument17 = new Position();
const Stave2Pos = new Position();
const Stave3Pos = new Position();
const Stave6Pos = new Position();
const Stave10Pos = new Position();
const Stave11Pos = new Position();

const note17_1_0 = new Position();

var shift13;
var shift17;

function insertTextToSVG(options) {

    var textContent = options.textContent;
    var strID = options.strID;
    var Stave_x = options.Stave_x || 0;
    var Stave_y = options.Stave_y || 0;
    var isOffset_x_abs = options.IsOffset_x_Abs || false;
    var Stave_x_Offset = options.Stave_x_Offset || 0;
    var Stave_y_Offset = options.Stave_y_Offset || 0;
    var StaveWidth = options.StaveWidth || 0;
    var StaveHeight = options.StaveHeight || 0;
    var StaveVerticalScale = options.StaveVerticalScale || 0;
    var fontSize = options.fontSize || 40;
    var fontFamily = options.fontFamily || "Bravura, Arial";
    var shift_x = options.shift_x || [0];
    var offset_sum = 0;
    var Stave_x_Offset_Value = 0;
    var Stave_y_Offset_Value = 0;
    var last_Stave_x_Offset = 0;
    var last_Stave_y_Offset = 0;
    var last_textContent = "";
    shift_x.forEach(function(offset, index) {
        offset_sum = offset_sum + offset;
        var newText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        newText.setAttribute('id', strID + '_' + index); // テキスト要素にIDを付ける
        newText.setAttribute('x', 0);
        newText.setAttribute('y', 0);
        newText.setAttribute('font-family', fontFamily);
        newText.setAttribute('font-size', fontSize);
        newText.setAttribute('fill', 'black');


        if(typeof textContent === "string"){
          newText.textContent = textContent;
        }
        else{
          if(textContent.length - 1 < index){
            newText.textContent = last_textContent;
          }
          else{
            newText.textContent = textContent[index];
            last_textContent = textContent[index];
          }
        }

        if(Stave_x_Offset.length - 1 < index){
          Stave_x_Offset_Value = last_Stave_x_Offset;
        }
        else{
          if(Stave_x_Offset.length >= 2){
            Stave_x_Offset_Value = Stave_x_Offset[index];
            last_Stave_x_Offset = Stave_x_Offset[index];
          }
          else{
            Stave_x_Offset_Value = Stave_x_Offset;
          }
        }

        if(Stave_y_Offset.length - 1 < index){
          Stave_y_Offset_Value = last_Stave_y_Offset;
        }
        else{
          if(Stave_y_Offset.length >= 2){
            Stave_y_Offset_Value = Stave_y_Offset[index];
            last_Stave_y_Offset = Stave_y_Offset[index];
          }
          else{
            Stave_y_Offset_Value = Stave_y_Offset;
          }
        }
        svgElement.appendChild(newText);
        (function() {
            var textWidth = newText.getBBox().width;
            var textHeight = newText.getBBox().height;
            var horizontalScale;
            if (typeof StaveWidth === 'undefined' || StaveWidth == 0) {
                horizontalScale = 1;
            } 
            else {
                horizontalScale = StaveWidth / textWidth;
            }
            var verticalScale;
            if (typeof StaveHeight === 'undefined' || StaveHeight == 0) {
                verticalScale = 1;
            } 
            else if (StaveVerticalScale != 0) {
                verticalScale = StaveVerticalScale;
            } 
            else {
                verticalScale = StaveHeight / textHeight;
            }
            if(isOffset_x_abs){
              var StavePos_x = offset.x + Stave_x_Offset_Value;
              var StavePos_y = offset.y + Stave_y_Offset_Value;
            }
            else{
              var StavePos_x = Stave_x + Stave_x_Offset + offset_sum;
              var StavePos_y = Stave_y + Stave_y_Offset;
            }

            newText.setAttribute('transform', 'translate(' + StavePos_x + ',' + StavePos_y + ') scale(' + horizontalScale + ',' + verticalScale + ')');
        })();

        svgElement.appendChild(newText);
    });
}

var allUniqueIds = [];
(function(){
function addShift(notes, arrx = [], arry = []) {
 
  let tempnote;
  let retShift = [];
  
  for(let i = 0; i < arrx.length || i == 0; i++){
    const pos = new Position();
    //notesのchildrenの各要素について処理
    if(arrx.length === 0){
      tempnote = notes;
    }
    else{
      tempnote = notes[arrx[i]];
      temp_y = arry[i];
    }
    pos.x = tempnote.getAbsoluteX();
    pos.y = tempnote.getStave().getYForLine(temp_y);

    retShift.push(pos);
  }
  return retShift;
}

var UniqueIds;
function getUniqueNoteheadIds(notes, arr = []) {
    //すべてのidを格納するためのセットを作成
    let tempnote;
    uniqueIds = new Set();
    for(let i = 0; i < arr.length || i == 0; i++){
    //notesのchildrenの各要素について処理
      if(arr.length === 0){
        tempnote = notes;
      }
      else{
        tempnote = notes[arr[i]];
      }
      tempnote.children.forEach(child => {
        //typeが"notehead"であるかチェックし、idを取得
        if (child.attrs){
          if(child.attrs.type === "NoteHead") {
            uniqueIds.add(child.attrs.id);
          }
        }
      });
    }
    // セットを配列に変換して戻り値として返す
    return Array.from(uniqueIds);
}

function updateAllUniqueIds(UniqueIds) {
    // allUniqueIdsにUniqueIdsを追加または結合
    if (allUniqueIds.length === 0) {//allUniqueIdsはグローバルな変数
      // allUniqueIdsが空の場合、UniqueIdsをそのままコピー
      allUniqueIds = [...UniqueIds];//スプレッド演算子で要素の中身を書き出す。
    } else {
      UniqueIds.forEach(id => {
        if (!allUniqueIds.includes(id)) {
            allUniqueIds.push(id);
        }
      });
    }
    // 更新されたallUniqueIdsを戻り値として返す
    return allUniqueIds;
}

function dotted(staveNote, noteIndex = -1) {
  if (noteIndex < 0) {
    Dot.buildAndAttach([staveNote], {
      all: true
    });
  } 
  else {
    for(noteIndexValue of noteIndex){
      Dot.buildAndAttach([staveNote], {
        index: noteIndexValue
      });
    }
  }
  return staveNote;
}

const {
  Factory,
  Stave,
  StaveNote,
  Formatter,
  Voice,
  StaveTie,
  BarLine,
  Beam,
  Dot,
  StaveConnector,
  Modifier,
  RenderContext,
  TextDynamics,
  Articulation,
  TextNote,
  Crescendo,
  Renderer
} = Vex.Flow;

let nscale = 0.64;
let nwidth = 1040;
let nheight = 1120;

let nHeadMargin = 70;
let nStaveWidth = 350;

const f = new Factory({ 
  renderer: { elementId: 'yonet202403Mid_Output01', width: nwidth, height: nheight * nscale }
  });
const ctx = f.getContext();
ctx.scale(nscale, nscale);

const defaultStyle = {
  lineWidth: ctx.lineWidth,
  strokeStyle: ctx.strokeStyle,
};

for (let i = 0; i <= nwidth * (1 / nscale); i += 10) {
  ctx.beginPath();
  ctx.moveTo(0 + i, 0);
  ctx.lineTo(0 + i, nheight);
  if (i % 100 === 0){
    ctx.setLineWidth(1);
    ctx.setStrokeStyle('rgba(200, 200, 200, 0.8)');
  }
  else{
    ctx.setLineWidth(0.5);
    ctx.setStrokeStyle('rgba(230, 230, 230, 0.8)');
  }
  ctx.stroke();
}

for (let i = 0; i <= nheight; i += 10) {
  ctx.beginPath();
  ctx.moveTo(0, i);
  ctx.lineTo(nwidth * (1 / nscale), i);
  if (i % 100 === 0){
    ctx.setLineWidth(1);
    ctx.setStrokeStyle('rgba(200, 200, 200, 0.8)');
  }
  else{
    ctx.setLineWidth(0.5);
    ctx.setStrokeStyle('rgba(230, 230, 230, 0.8)');
  }
  ctx.stroke();
}

ctx.lineWidth = defaultStyle.lineWidth;
ctx.strokeStyle = defaultStyle.strokeStyle;

const stave1 = new Stave(80, 150, nHeadMargin + nStaveWidth).setContext(ctx);
stave1.setClef("treble").setContext(ctx);
stave1.setTimeSignature('4/4').setContext(ctx);
stave1.setMeasure(1);
stave1.draw();

Instrument1.x = stave1.x - 30;
Instrument1.y = stave1.y + 90; 

const notes1 = [
  new StaveNote({ keys: ["c/4"], duration: "4" }),
  new StaveNote({ keys: ["d/4"], duration: "4" }),
  new StaveNote({ keys: ["e/4"], duration: "4" }),
  new StaveNote({ keys: ["f/4"], duration: "4" })
];

var stave1Voice = new Vex.Flow.Voice({ num_beats: 4, beat_value: 4 });
stave1Voice.setStrict(true);
stave1Voice.addTickables(notes1);

var formatter1 = new Vex.Flow.Formatter().joinVoices([stave1Voice]);
formatter1.formatToStave([stave1Voice], stave1);
stave1Voice.draw(ctx, stave1);

const stave2 = f.Stave({ x: stave1.width + stave1.x, y: stave1.y, width: nStaveWidth });
stave2.setMeasure(2);
stave2.setContext(ctx).draw();

Stave2Pos.x = stave2.x;
Stave2Pos.y = stave2.y;
//f.draw();

const stave3 = new Stave(stave2.width + stave2.x, stave1.y, nStaveWidth).setContext(ctx);
stave3.setMeasure(3);
stave3.draw();

Stave3Pos.x = stave3.x;
Stave3Pos.y = stave3.y;

const stave4 = new Stave(stave3.width + stave3.x, stave1.y, nStaveWidth).setContext(ctx);
stave4.setMeasure(4);
stave4.draw();

const stave5 = new Stave(stave1.x, stave1.y + 200, nHeadMargin + nStaveWidth).setContext(ctx);
stave5.addClef("treble").setContext(ctx);
stave5.addTimeSignature('4/4').setContext(ctx);
stave5.setMeasure(5);
stave5.draw();

var connector = new VF.StaveConnector(stave1, stave5);
connector.setType(VF.StaveConnector.type.SINGLE);
connector.setContext(ctx);
connector.draw();



const stave6 = new Stave(stave5.width + stave5.x, stave5.y, nStaveWidth).setContext(ctx);
stave6.setMeasure(6);
stave6.draw();

Stave6Pos.x = stave6.x;
Stave6Pos.y = stave6.y;

const stave7 = new Stave(stave6.width + stave6.x, stave5.y, nStaveWidth).setContext(ctx);
stave7.setMeasure(7);
stave7.draw();

const stave8 = new Stave(stave7.width + stave7.x, stave5.y, nStaveWidth).setContext(ctx);
stave8.setMeasure(8);
stave8.draw();

const stave9 = new Stave(stave5.x, stave5.y + 200, nHeadMargin + nStaveWidth).setContext(ctx);
stave9.setMeasure(9);
stave9.draw();

var connector9 = new VF.StaveConnector(stave5, stave9);
connector9.setType(VF.StaveConnector.type.SINGLE);
connector9.setContext(ctx);
connector9.draw();

var connector9_2 = new VF.StaveConnector(stave5, stave9);
connector9_2.setType(VF.StaveConnector.type.BRACKET);
connector9_2.setContext(ctx);
connector9_2.draw();

Instrument2.x = stave1.x - 30;
Instrument2.y = stave5.y + ((stave9.y - stave5.y) / 2) + 90; 

const stave10 = new Stave(stave9.width + stave9.x, stave9.y, nStaveWidth).setContext(ctx);
stave10.setMeasure(10);
stave10.draw();

Stave10Pos.x = stave10.x;
Stave10Pos.y = stave10.y;

const stave11 = new Stave(stave10.width + stave10.x, stave9.y, nStaveWidth).setContext(ctx);
stave11.setMeasure(11);
stave11.draw();

Stave11Pos.x = stave11.x;
Stave11Pos.y = stave11.y;

const stave12 = new Stave(stave11.width + stave11.x, stave9.y, nStaveWidth).setContext(ctx);
stave12.setMeasure(12);
stave12.draw();


const stave13 = new Stave(stave9.x, stave9.y + 200, nHeadMargin + nStaveWidth).setContext(ctx);
stave13.setMeasure(13);
stave13.addClef("bass").setContext(ctx);
stave13.addTimeSignature('4/4').setContext(ctx);
stave13.draw();

Instrument13.x = stave13.x - 30;
Instrument13.y = stave13.y + 90; 

const stave13_1 = new Stave(nHeadMargin + stave9.x, stave9.y + 200, 0).setContext(ctx);
stave13_1.setBegBarType(VF.Barline.type.NONE);
stave13_1.setEndBarType(VF.Barline.type.NONE);
stave13_1.draw();

const notes13_1 = [
  new StaveNote({ keys: ["f/4"], duration: "4", stem_direction: -1 }),
  new StaveNote({ keys: ["c/4"], duration: "4r" }),
  new StaveNote({ keys: ["c/4"], duration: "8r" }),
  new StaveNote({ keys: ["f/4"], duration: "8", stem_direction: -1 }),
  new StaveNote({ keys: ["c/4"], duration: "8r" }),
  new StaveNote({ keys: ["f/4"], duration: "8", stem_direction: -1 })
];
const beam13_1 = new VF.Beam([notes13_1[3],notes13_1[5]]);

var stave13_1Voice = new Vex.Flow.Voice({ num_beats: 4, beat_value: 4 });
stave13_1Voice.setStrict(true);
stave13_1Voice.addTickables(notes13_1);

//var formatter13_1 = new Vex.Flow.Formatter().joinVoices([stave13_1Voice]);
//formatter13_1.formatToStave([stave13_1Voice], stave13_1);
//formatter13_1.format([stave13_1Voice], nStaveWidth - 30);
//stave13_1Voice.draw(ctx, stave13_1);



const stave13_2 = new Stave(nHeadMargin + stave9.x, stave9.y + 200, 0).setContext(ctx);
stave13_2.setBegBarType(VF.Barline.type.NONE);
stave13_2.setEndBarType(VF.Barline.type.NONE);
stave13_2.draw();

const notes13_2 = [
  new VF.StaveNote({ keys: ["g/5"], duration: "8", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["g/5"], duration: "8", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["c/5"], duration: "8", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["g/5"], duration: "16", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["c/5"], duration: "16", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["g/5"], duration: "8", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["g/5"], duration: "8", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["c/5"], duration: "8", stem_direction: 1 }),
  new VF.StaveNote({ keys: ["g/5"], duration: "8", stem_direction: 1 })
];

const notes13_3 = [
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),

  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),

  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),

  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 }),
  new VF.GhostNote({ keys: ["a/5"], duration: "16", stem_direction: 1 })
];

UniqueIds = getUniqueNoteheadIds(notes13_2, [0, 1, 3, 5, 6, 8]);
allUniqueIds = updateAllUniqueIds(UniqueIds);

const beam13_2_1 = new VF.Beam([notes13_2[0], notes13_2[1]]);
const beam13_2_2 = new VF.Beam([notes13_2[2], notes13_2[3], notes13_2[4]]);
const beam13_2_3 = new VF.Beam([notes13_2[5], notes13_2[6], notes13_2[7], notes13_2[8]]);

var stave13_2Voice = new Vex.Flow.Voice({ num_beats: 4, beat_value: 4 });
stave13_2Voice.setStrict(true);
stave13_2Voice.addTickables(notes13_2);

var stave13_3Voice = new Vex.Flow.Voice({ num_beats: 4, beat_value: 4 });
stave13_3Voice.setStrict(true);
stave13_3Voice.addTickables(notes13_3);

var formatter13_2 = new Vex.Flow.Formatter().joinVoices([stave13_3Voice, stave13_1Voice, stave13_2Voice]);
//formatter13_2.formatToStave([stave13_3Voice, stave13_1Voice, stave13_2Voice], stave13_2);
formatter13_2.format([stave13_3Voice, stave13_1Voice, stave13_2Voice], nStaveWidth - 30);
stave13_1Voice.draw(ctx, stave13_2);
stave13_2Voice.draw(ctx, stave13_2);

beam13_1.setContext(ctx).draw();

beam13_2_1.setContext(ctx).draw();
beam13_2_2.setContext(ctx).draw();
beam13_2_3.setContext(ctx).draw();

shift13 = addShift(
  notes13_2, 
  [0, 1, 2, 3, 5, 5, 6, 6, 7, 7, 8, 8],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
);


const stave14 = new Stave(stave13.width + stave13.x, stave13.y, nStaveWidth).setContext(ctx);
stave14.setMeasure(14);
stave14.draw();


const stave15 = new Stave(stave14.width + stave14.x, stave13.y, nStaveWidth).setContext(ctx);
stave15.setMeasure(15);
stave15.draw();


const stave16 = new Stave(stave15.width + stave15.x, stave13.y, nStaveWidth).setContext(ctx);
stave16.setMeasure(16);
stave16.draw();


const stave17 = new Stave(stave13.x, stave13.y + 200, nHeadMargin + nStaveWidth).setContext(ctx);
stave17.setMeasure(17);
stave17.addTimeSignature('4/4').setContext(ctx);

const stave17_1 = new Stave(nHeadMargin + stave13.x, stave13.y + 200, 0).setContext(ctx);
stave17_1.setBegBarType(VF.Barline.type.NONE);
stave17_1.setEndBarType(VF.Barline.type.NONE);
stave17_1.draw();

for (var i = 0; i < 5; i++) {
  if (i == 2) continue;
  stave17.setConfigForLine(i, {visible: false} );
}

stave17.draw();

Instrument17.x = stave17.x - 30;
Instrument17.y = stave17.y + 90; 

var connector17 = new VF.StaveConnector(stave9, stave17);
connector17.setType(VF.StaveConnector.type.SINGLE);
connector17.setContext(ctx);
connector17.draw();

const notes17_1 = [
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),

  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),

  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),

  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 }),
  new VF.StaveNote({ keys: ["a/4"], duration: "16", stem_direction: -1 })
];
UniqueIds = getUniqueNoteheadIds(notes17_1, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
allUniqueIds = updateAllUniqueIds(UniqueIds);

const beam17_1_1 = new VF.Beam([notes17_1[0], notes17_1[1], notes17_1[2], notes17_1[3]]);
const beam17_1_2 = new VF.Beam([notes17_1[4], notes17_1[5], notes17_1[6], notes17_1[7]]);
const beam17_1_3 = new VF.Beam([notes17_1[8], notes17_1[9], notes17_1[10], notes17_1[11]]);
const beam17_1_4 = new VF.Beam([notes17_1[12], notes17_1[13], notes17_1[14], notes17_1[15]]);

var stave17_1Voice = new Vex.Flow.Voice({ num_beats: 4, beat_value: 4 });
stave17_1Voice.setStrict(true);
stave17_1Voice.addTickables(notes17_1);

var formatter17_1 = new Vex.Flow.Formatter().joinVoices([stave17_1Voice]);
//formatter17_1.formatToStave([stave17_1Voice], stave17_1);
formatter17_1.format([stave17_1Voice], nStaveWidth - 30);
stave17_1Voice.draw(ctx, stave17_1);

beam17_1_1.setContext(ctx).draw();
beam17_1_2.setContext(ctx).draw();
beam17_1_3.setContext(ctx).draw();
beam17_1_4.setContext(ctx).draw();

note17_1_0.x = notes17_1[0].getAbsoluteX();
note17_1_0.y = notes17_1[0].getStave().getYForLine(1);

shift17 = addShift(
  notes17_1, 
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  [4, 4, 4, 4, 4, 4, 4, 4, 4, 4,  4,  4,  4,  4,  4,  4]
);

const stave18 = new Stave(stave17.width + stave17.x, stave17.y, nStaveWidth).setContext(ctx);
stave18.setMeasure(18);

for (var i = 0; i < 5; i++) {
  if (i == 2) continue;
  stave18.setConfigForLine(i, {visible: false} );
}

stave18.draw();

const stave19 = new Stave(stave18.width + stave18.x, stave18.y, nStaveWidth).setContext(ctx);
stave19.setMeasure(19);

for (var i = 0; i < 5; i++) {
  if (i == 2) continue;
  stave19.setConfigForLine(i, {visible: false} );
}

stave19.draw();

const stave20 = new Stave(stave19.width + stave19.x, stave19.y, nStaveWidth).setContext(ctx);
stave20.setMeasure(20);

for (var i = 0; i < 5; i++) {
  if (i == 2) continue;
  stave20.setConfigForLine(i, {visible: false} );
}

stave20.draw();

})();

const svgElement2 = document.querySelector('#yonet202403Mid_Output01 svg');
svgElement2.style.backgroundColor = '#F5F5F5';
var svgContainer = document.getElementById('yonet202403Mid_Output01');
var svgElement = svgContainer.querySelector('svg');

var newText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText.setAttribute('x', '100');
newText.setAttribute('y', '100');
newText.setAttribute('font-family', 'Hiragino Kaku Gothic Pro, メイリオ, MS Gothic, sans-serif');
newText.setAttribute('font-size', '50');
newText.setAttribute('fill', 'black');
newText.textContent = 'TestTitle - subTitle - lyrics: yo-net, music: yo-net';
svgElement.appendChild(newText);

var newText2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText2.setAttribute('x', Instrument1.x);
newText2.setAttribute('y', Instrument1.y);
newText2.setAttribute('font-family', 'Bravura, VexFlow, Arial, sans-serif');
newText2.setAttribute('font-size', '20pt');
newText2.setAttribute('fill', 'black');
newText2.textContent = 'Vocal';
var textGroup2 = document.createElementNS('http://www.w3.org/2000/svg', 'g');
textGroup2.setAttribute('transform', 'rotate(-90 ' + Instrument1.x + ' ' + Instrument1.y + ')');
textGroup2.appendChild(newText2);
svgElement.appendChild(textGroup2);

var newText3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText3.setAttribute('x', Instrument2.x);
newText3.setAttribute('y', Instrument2.y);
newText3.setAttribute('font-family', 'Bravura, VexFlow, Arial, sans-serif');
newText3.setAttribute('font-size', '20pt');
newText3.setAttribute('fill', 'black');
newText3.textContent = 'E.Guitar';
var textGroup3 = document.createElementNS('http://www.w3.org/2000/svg', 'g');
textGroup3.setAttribute('transform', 'rotate(-90 ' + Instrument2.x + ' ' + Instrument2.y + ')');
textGroup3.appendChild(newText3);
svgElement.appendChild(textGroup3);

var newText13 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText13.setAttribute('x', Instrument13.x);
newText13.setAttribute('y', Instrument13.y);
newText13.setAttribute('font-family', 'Bravura, VexFlow, Arial, sans-serif');
newText13.setAttribute('font-size', '20pt');
newText13.setAttribute('fill', 'black');
newText13.textContent = 'Drum';
var textGroup13 = document.createElementNS('http://www.w3.org/2000/svg', 'g');
textGroup13.setAttribute('transform', 'rotate(-90 ' + Instrument13.x + ' ' + Instrument13.y + ')');
textGroup13.appendChild(newText13);
svgElement.appendChild(textGroup13);

var newText17 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText17.setAttribute('x', Instrument17.x);
newText17.setAttribute('y', Instrument17.y);
newText17.setAttribute('font-family', 'Bravura, VexFlow, Arial, sans-serif');
newText17.setAttribute('font-size', '20pt');
newText17.setAttribute('fill', 'black');
newText17.textContent = 'Percussion';
var textGroup17 = document.createElementNS('http://www.w3.org/2000/svg', 'g');
textGroup17.setAttribute('transform', 'rotate(-90 ' + Instrument17.x + ' ' + Instrument17.y + ')');
textGroup17.appendChild(newText17);
svgElement.appendChild(textGroup17);

//設定
var fontSize2 = 40; // フォントサイズ
var fontFamily2 = "Bravura, Arial"; //Bravuraフォントファミリー
var textContent2 = "\uE500";//符頭E0A4

// テキスト要素の作成
var newText2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText2.setAttribute('id', 'rest2'); //テキスト要素にIDを付ける
newText2.setAttribute('x', 0);
newText2.setAttribute('y', 0);
newText2.setAttribute('font-family', fontFamily2);
newText2.setAttribute('font-size', fontSize2);
newText2.setAttribute('fill', 'black');
newText2.textContent = textContent2;

// SVG要素にテキストを追加
svgElement.appendChild(newText2);

(function(){
    var textWidth = document.getElementById('rest2').getBBox().width;
    var textHeight = document.getElementById('rest2').getBBox().height;

    //スケーリング
    var horizontalScale = 1;
    var verticalScale = 1;

    var StavePos_x = Stave2Pos.x + 170;
    var StavePos_y = Stave2Pos.y + 60;

    newText2.setAttribute('transform', 'translate(' + StavePos_x  + ',' + StavePos_y + ') scale(' + horizontalScale + ',' + verticalScale + ')');

    //SVG要素に追加する
    svgElement.appendChild(newText2);
})();


//設定
var fontSize3 = 40; // フォントサイズ
var fontFamily3 = "Bravura, Arial"; //Bravuraフォントファミリー
var textContent3 = "\uE501";//符頭E0A4

// テキスト要素の作成
var newText3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText3.setAttribute('id', 'rest3'); // テキスト要素にIDを付ける
newText3.setAttribute('x', 0);
newText3.setAttribute('y', 0);
newText3.setAttribute('font-family', fontFamily3);
newText3.setAttribute('font-size', fontSize3);
newText3.setAttribute('fill', 'black');
newText3.textContent = textContent3;

// SVG要素にテキストを追加
svgElement.appendChild(newText3);

(function(){
    var textWidth = document.getElementById('rest3').getBBox().width;
    var textHeight = document.getElementById('rest3').getBBox().height;

    //スケーリング
    var horizontalScale = 1;
    var verticalScale = 1;

    var StavePos_x = Stave3Pos.x + 335;
    var StavePos_y = Stave3Pos.y + 60;

    newText3.setAttribute('transform', 'translate(' + StavePos_x  + ',' + StavePos_y + ') scale(' + horizontalScale + ',' + verticalScale + ')');

    //SVG要素に追加する
    svgElement.appendChild(newText3);
})();

//設定
var fontSize6 = 40; // フォントサイズ
var fontFamily6 = "Bravura, Arial"; //Bravuraフォントファミリー
var textContent6 = "\uE502";//符頭E0A4

// テキスト要素の作成
var newText6 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText6.setAttribute('id', 'rest6'); // テキスト要素にIDを付ける
newText6.setAttribute('x', 0);
newText6.setAttribute('y', 0);
newText6.setAttribute('font-family', fontFamily6);
newText6.setAttribute('font-size', fontSize6);
newText6.setAttribute('fill', 'black');
newText6.textContent = textContent6;

// SVG要素にテキストを追加
svgElement.appendChild(newText6);

(function(){
    var textWidth = document.getElementById('rest6').getBBox().width;
    var textHeight = document.getElementById('rest6').getBBox().height;

    //スケーリング
    var horizontalScale = 1;
    var verticalScale = 1;

    var StavePos_x = Stave6Pos.x + 325;
    var StavePos_y = Stave6Pos.y + 60;

    newText6.setAttribute('transform', 'translate(' + StavePos_x  + ',' + StavePos_y + ') scale(' + horizontalScale + ',' + verticalScale + ')');

    // クレシェンド記号をSVG要素に追加する
    svgElement.appendChild(newText6);
})();

//設定
var fontSize10 = 40; // フォントサイズ
var fontFamily10 = "Bravura, Arial"; // Bravuraフォントファミリー
var textContent10 = "\uE503\uE504\uE504\uE504\uE504\uE505";// 符頭E0A4

// テキスト要素の作成
var newText10 = document.createElementNS('http://www.w3.org/2000/svg', 'text');
newText10.setAttribute('id', 'rest10'); // テキスト要素にIDを付ける
newText10.setAttribute('x', 0);
newText10.setAttribute('y', 0);
newText10.setAttribute('font-family', fontFamily10);
newText10.setAttribute('font-size', fontSize10);
newText10.setAttribute('fill', 'black');
newText10.textContent = textContent10;

// SVG要素にテキストを追加
svgElement.appendChild(newText10);

(function(){
    var textWidth = document.getElementById('rest10').getBBox().width;
    var textHeight = document.getElementById('rest10').getBBox().height;

    //スケーリング
    var horizontalScale = 1;
    var verticalScale = 1;

    var StavePos_x = Stave10Pos.x + 325;
    var StavePos_y = Stave10Pos.y + 60;

    newText10.setAttribute('transform', 'translate(' + StavePos_x  + ',' + StavePos_y + ') scale(' + horizontalScale + ',' + verticalScale + ')');

    //SVG要素に追加する
    svgElement.appendChild(newText10);
})();



var options = {
    textContent: ["\uE503", "\uE504", "\uE504", "\uE504", "\uE504", "\uE504", "\uE504", "\uE504", "\uE504", "\uE505"], // 必須文字列
    strID: "rest11", // 必須
    Stave_x: Stave11Pos.x,
    Stave_y: Stave11Pos.y,
    Stave_x_Offset: 305, // オプション、デフォルトは0
    Stave_y_Offset: 60, // オプション、デフォルトは0
    StaveWidth: 0, // オプション、デフォルトは0
    StaveHeight: 0, // オプション、デフォルトは0
    StaveVerticalScale: 0, // オプション、デフォルトは0
    fontSize: 40, // オプション、デフォルトは40
    fontFamily: "Bravura, Arial", // オプション、デフォルトは"Bravura, Arial"
    shift_x: [0, 0, 10, 10, 10, 10, 10, 10, 10, 15], // xのオフセット値配列
    IsOffset_x_Abs: false
};
insertTextToSVG(options);

var note13_2_0_option = {
    textContent: ["\uFF65", "\uFF65", "\uFF65", "\uFF65", 
                  "\uFF65", "\uFF68", "\uFF66", "\uFF67", "\uFF65", "\uFF0B", "\uFF65", "\uFF0F"], // 必須文字列
                 //x      ,   half_o,         ,        >,         ,       + ,         ,        o
    strID: "note13_2_0", // 必須
    Stave_y_Offset: [   -5,       -5,       -5,       -5,
                        -5,      -60,       -5,      -60,       -5,      -60,       -5,      -60],
    fontFamily: "YonetMuFL, Arial", // オプション、デフォルトは"Bravura, Arial"
    shift_x: shift13, // xのオフセット値配列
    IsOffset_x_Abs: true
};
insertTextToSVG(note13_2_0_option);

var note17_1_0_Shaker_option = {
    textContent: ["< Shaker >"], // 必須文字列
    strID: "note17_1_0", // 必須
    Stave_x: note17_1_0.x,
    Stave_y: note17_1_0.y,
    Stave_x_Offset: -20,
    Stave_y_Offset: -40,
    fontSize: 60,
    fontFamily: "YonetMuFL, Arial", // オプション、デフォルトは"Bravura, Arial"
    shift_x: [0] // xのオフセット値配列
};
insertTextToSVG(note17_1_0_Shaker_option);

var note17_1_0_option = {
    textContent: ["\uFF69"], // 必須文字列
    strID: "note17_1_0", // 必須
    Stave_y_Offset: -5,
    fontFamily: "YonetMuFL, Arial", // オプション、デフォルトは"Bravura, Arial"
    shift_x: shift17, // xのオフセット値配列
    IsOffset_x_Abs: true
};
insertTextToSVG(note17_1_0_option);

// 透明にするIDの配列
// 例としてここでIDを指定
let autoUniqueIds = allUniqueIds.map(id => "vf-" + id);

// 各IDに対して処理
autoUniqueIds.forEach(id => {
    // 該当するIDの要素を取得
    let element = svgElement.getElementById(id);
    if (element) {
        // 該当する要素があれば、描画内容を透明にする
        let paths = element.querySelectorAll("path");
        paths.forEach(path => {
            path.setAttribute("fill", "none");
            path.setAttribute("stroke", "none");
        });
    }
});

})();
</script>


 VexFlowの技術とは関係のない記事になってしまいましたが、またひとつ奥の手の使い方を示せましたね。


 自作の関数の使い方を説明します。


  • addShift(StaveNote, Array of StaveNoteElementNumber, Array of StaveNote.getStave().getYForLine(Number))

 この関数は3つの引数を受け取り、自作のPositionクラス(.xと.yだけのメンバを持つ座標)の配列を返却します。


第一引数:おそらく配列化されているであろう一小節分のStaveNoteのオブジェクト名を受け取ります。どの配列のStaveNoteの要素にアクセスするかは次の第二引数で指定するからです。つまりStaveNoteが配列化されていない場合は、この関数は使えません。


第二引数:アクセスして座標取得したいStaveNoteの要素を指定します。座標を何回か使いたい場合もありますので、同じ要素番号を指定することも可能です。要素ごとのx座標は同じ値を持つので、同じ座標値が配列の中で並びますが、やりたいことでもあるので問題ありません。また第三引数によっては同じStaveNoteの要素でも、.y座標値が変わります。


第三引数:第二引数で指定したStaveNoteの五線譜の一番上を1とした座標値を取得できます。五線譜の間隔は10px相当となっています。五線譜の一番下なら5ですし、さらにその範囲の外なら0や負の値、5より大きい値を使うこともできます。このような値を配列にしたものを設定します。


 このようにして取得した返却値はさらに自作の関数insertTextToSVGの引数のキーshift_xの値として設定して、isOffset_x_absキーのブール値をtrueにすることで、取得した座標に指定したテキストを一気に配置することができます。


 例えば、以下のようにすると

shift13 = addShift(
  notes13_2, 
  [0, 1, 2, 3, 5, 5, 6, 6, 7, 7, 8, 8],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
);


 notes13_2というStaveNoteオブジェクトの配列0~8まで、5~8は2回ずつ使うようにして、第3引数は全て1なので、五線譜の一番上の座標を取得できます。


 次に


  • insertTextToSVG(option)


 この関数は、optionという引数で指定したオブジェクトの内容に従って、SVG内にテキストを配置する仕組みになっています。svgElementというグローバル変数でsvgタグエレメントを保持しておく必要があります。


var svgContainer = document.getElementById('yonet202403Mid_Output01');
var svgElement = svgContainer.querySelector('svg');


という感じでsvgElementというグローバル変数を定義します。上記であれば

のようにしていたところにVexFlowのFactory内で定義した要素yonet202403Mid_Output01に対してsvgタグが作られるので、上記divタグの中にあるsvgタグをsvgElementが保持してい状態になります。


第一引数:この関数専用のオブジェクトを指定します。以下のようなキーを設定します。


textContent:文字列を配列あるいは文字列で定義します。配列になっている場合はshift_xの対応する要素に対しての文字列になります。楽譜記号である可能性があるので普通の文字列では表せないコードポイントである可能性がありますので、その場合は\u(16進数1桁~8桁)で表します。4桁以内であることが多いと思います。例えば"\uE501\uE502"、["\uE501", "\uE502"]、["< Shaker >"]のような値が有効です。必須です。shift_xに対して要素が足りない場合は最後の要素値が使われます。


strID:適当な唯一のIDをつけます。あとで探して、改造する必要がある場合に有用なIDとなりますので、名づけをしておくと便利な場合もあれば、あとあと使う予定もない場合には名前を付けるのが嫌になってくる場合もありますが、名前を付けます。shift_xの要素番号に対応したサフィックス(_要素番号)がIDには付与されます。


Stave_x 0:isOffset_x_absキーがtrueのときは使われない値になります。省略可能です。 isOffset_x_absキーがfalseなのに省略すると規定値は0なので、描画領域内に文字が貼り付けられないと思います。

Stave_y 0:x値と同様です。y座標として機能します。


isOffset_x_abs:shift_xで使う値が絶対値座標なのかどうかを指定します。規定値はfalseで、前のテキストの相対値になります。この関数は横にテキストを並べたいときに使うつもりで作った関数だから規定値はfalseです。


Stave_x_Offset:Stave_Xやshift_xで指定した座標からのOffsetのx座標を指定できます。配列にするとshift_xの要素に対応した値が採用されます。規定値は0です。shift_xに対して要素が足りない場合は最後の要素値が使われます。

Stave_y_Offset:x値と同様です。y座標として機能します。


StaveWidth:目指す横幅を設定します。うまく機能しない場合もあります。省略可能です。

StaveHeight:目指す縦幅を設定します。うまく機能しない場合もあります。。省略可能です。


StaveVerticalScale:StaveHeightが機能しない場合に設定すると縦の倍率が調整できます。。省略可能です。


fontSize:フォントの大きさを指定します。40がちょうどいいみたいなので、40が規定値になっています。


fontFamily:フォントファミリ名を設定します。規定値は"Bravura, Arial"です。BravuraがなければArialです。Windowsのフォントかな?


shift_x:よこにずらしていく座標値を配列で指定します。これを指定しない場合は[0]で機能します。この値を使いこなすのがこの関数の醍醐味ですが、単純に一文字表示するのにも便利は便利なので配列要素が1個でもいいですね。isOffset_x_absがtrueのときは絶対値として機能しますので、y座標値も含んだ[{x: 0, y: 0}, {x: 0, y: 0}, …]のような形式である必要があります。addShift関数からの戻り値がこのような形式になっています。


 それもこれも、符頭を消す処理が無ければできないことなので、符頭を消すNoteHeadの番号を集める処理が必要です。グローバル変数のallUniqueIdsが必要です。


 getUniqueNoteheadIds関数を以下のようにするとIDを取得できます。


  • getUniqueNoteheadIds(StaveNote, Array of StaveNoteElementNumber)


第一引数:第二引数を指定する場合はStaveNoteオブジェクトを指定するか、第二引数を省略する場合はStaveNoteオブジェクトの配列要素を指定します。


第二引数:StaveNoteオブジェクトを指定した場合は、ここで、取得したい要素の配列を設定します。


 戻り値を使って次の符頭の配列を構築する関数を実行するとallUniqueIdsが完成します。


  • updateAllUniqueIds(return of getUniqueNoteheadIds_Value)


第一引数:getUniqueNoteheadIdsを設定します。戻り値はグローバル変数allUniqueIdsで格納します。


 戻り値には消したい符頭のアイテムが揃った状態が構築されます。


以下のように使います。allUniqueIdsは名前も変えられない固定のグローバル変数です。UniqueIdsは一時的に使う橋渡しをするだけの変数なので、どんな名前でもいいです。


UniqueIds = getUniqueNoteheadIds(notes13_2, [0, 1, 3, 5, 6, 8]);
allUniqueIds = updateAllUniqueIds(UniqueIds);


 allUniqueIdsは886行目から900行目の処理によって、符頭が非表示になります。


 一線譜を描く場合はStaveクラスのオブジェクトを作成して、描画するまでの間に、Visbleをfalseにするという設定が必要で、以下のようにします。


  • (Staveクラスのオブジェクト).setConfigForLine(0~4, {visible: false} );


 setConfigForLine関数で設定を変えることができます。


第一引数:五線譜の上から0、1、…、4と対応しています。数値を設定します。


第二引数:visibleキーにfalseという値を持ったオブジェクトを指定します。


 なんども呼び出すのが面倒なのでfor文とif文を使って以下のように使うのが便利みたいです。


for (let i = 0; i < 5; i++) {
  if (i != 2){ 
    stave17.setConfigForLine(i, {visible: false} );
  }
}


 という感じです。今回のコードではもうちょっと違ったjavascriptの書き方をしています。覚えやすい方法で使うといいでしょう。

 

VexFlow 使い方に戻る。