0

次のようなコードがあります。

// highlight text
vi.prototype.parse = function (text) {
    // some code
    this.data = data;
};
// place it on canvas
vi.prototype.render = function () {
    /* loop */
        this.ctx.clearRect(/* ... */);
        this.ctx.fillStyle = this.data[i].bg;
        this.ctx.fillRect(/* ... */);
        this.ctx.fillText(data[i].text, /* ... */);
        // ....
    /* end loop */
};

テキストが変更されるたびに、テキストを解析してレンダリングします。線がキャンバスに入らないという事実により、すべてが複雑になります。

1 Some line
2 Some long line line line line line line line li
 ne line line
3 Some line

背景色と前景色を含むテキストを解析して保存する最良の方法は何ですか?

構文を強調表示してテキストを印刷する必要があります。テキストを解析して何らかの形式で返す関数があります。たとえば、

text = "var x;";
highlightedText = vi.parse (text);
console.log (highlightedText);
>> [[  {text: "var", fg: "#dd5", bg: "#000"}, 
       {text: " ", fg: "#FFF", bg: "#000"},         
       {text: "x", fg: "#5dd", bg: "#000"}, 
       {text: ";", fg: "#FFF", bg: "#000"}]];
// Displays the text in canvas
vi.render (highlightedText);

テキストデータの保存方法としては良くないと思います

4

1 に答える 1

0

これはテスト済みのコードではありませんが、私の考えは次のとおりです。

スタイル定義をメインクラスに保持します (vi?)

テキストを描画するために必要なすべてを備えた textSegment オブジェクトを作成します。

  • テキスト。
  • テキストのスタイル。
  • テキストの幅。

すべての textSegments をメイン クラスの配列に保持します。

    this.textSegments.push({ 
        text  : text, 
        textWidth : ctx.measureText(newText).width, 
        style : style 
    });

これがコードです(テストされていない/不完全です!):

function vi(context,lineheight){

    this.ctx=context;
    this.lineHeight=lineheight;
    this.textSegments=[];
    this.x=0;
    this.y=0;

    // keep the style definitions once and reference them in your text segments
    this.styles=[];
    this.styles["normal"]=   { font:"12px Arial", bg:"#000", fg:"#fff" };
    this.styles["operator"]= { font:"12px Arial", bg:"#000", fg:"#5dd" };
    this.styles["keywordS"]= { font:"12px Arial", bg:"#000", fg:"#d55" };

}
//
// usage: myVi.addTextSegment("Hello","normal");
//
vi.prototype.addTextSegment(text,style){

    // measure the text once while you're adding it
    this.ctx.font=newStyle.font;

    // create a textSegment object 
    // that has everything needed to draw the text
    this.textSegments.push({ 
        text  : text, 
        textWidth : ctx.measureText(newText).width, 
        style : style 
    });
}
// draw the textSegment
vi.prototype.drawTextSegment(textSegment){
    var style=this.styles[textSegment.style];
    this.ctx.save();
    this.ctx.font=textSegment.style.font;
    this.ctx.fillStyle=textSegment.style.bg;
    this.ctx.rect(this.x,this.y,textSegment.textWidth,this.lineHeight);
    this.drawText(textSegment.text,this.x,this.y);
    this.ctx.restore();
    this.x+=textSegment.textWidth;
}
于 2013-04-22T22:46:08.770 に答える