1

2 つのキャンバスとその中にテキストを含む小さなコードがあります。しかし、指定したキャンバスのフォント サイズを変更できません。

if(i==1) {
       c.getContext('2d').font = "35pt bold arial";   
}

以下のコードでは、2 番目のキャンバスのフォントを変更しようとしていますが、適用されていません。

JSFiddle - http://jsfiddle.net/9n6wD/

var myCanvas = document.createElement('canvas');
myCanvas.width=400;
myCanvas.height=200;
document.body.appendChild(myCanvas);
myCanvasCtx = myCanvas.getContext('2d');

var canvas1 = document.createElement('canvas');
canvas1.width = 150;
canvas1.height = 100;
var myCanvas1Ctx = canvas1.getContext('2d');
myCanvas1Ctx.fillStyle = "#000";
myCanvas1Ctx.font = "25pt arial";
myCanvas1Ctx.fillText("Hello",0,25);

var canvas2 = document.createElement('canvas');
canvas2.width = 150;
canvas2.height = 100;
var myCanvas2Ctx = canvas2.getContext('2d');
myCanvas2Ctx.fillStyle = "#000";
myCanvas2Ctx.font = "25pt arial";
myCanvas2Ctx.fillText("World!",0,25);

var arr = [];
arr.push(new Object({canvas : canvas1, xposition : 50}), new Object({canvas : canvas2, xposition : 170}) );

for(var i in arr) {
    var c = arr[i].canvas;
    if(i==1) {
       c.getContext('2d').font = "35pt bold arial";   
    }

     myCanvasCtx.drawImage(c, arr[i].xposition , 15, c.width, c.height); 
}
4

1 に答える 1

2

Html キャンバスは、ピクセルを使用してキャンバスにテキストを描画し、それらのピクセルを忘れます。

これを行う場合:

c.getContext('2d').font = "35pt bold arial";

以前にペイントしたテキストのフォントを変更していません。

新しいテキストのフォントを変更しています。

だから、あなたの「世界」を変えるために!35pt フォントにするには、次のことが必要です。

  1. キャンバスをクリアし、
  2. フォントを変更し、
  3. 「ワールド!」を塗り直します。

このようなもの:

// get a reference to the context of your desired canvas
var ctx=c.getContext('2d')

// clear that canvas
ctx.clearRect(0,0,c.width,c.height);

// reset the font 
ctx.font = "35pt bold arial";

// repaint the text
ctx.fillText("World!",0,25);

コード設計の代替として

画面外のキャンバスを使用して各単語を作成する代わりに、画面上のコンテキストでフォントを一時的に変更できます。

// draw text @x,y using a specified font

fillTextWidthFont(0,25,"35pt bold arial","World!");

// the function to draw text with a specified font

function fillTextWithFont(x,y,font,text){

    // save the context state (including the beginning font)
    myCanvasCtx.save();

    // change the context font to your desired font
    myCanvasCtx.font=font;

    // draw your text
    myCanvasCtx.fillText(text,x,y);

    // restore the context state (also restoring the beginning font)
    myCanvasCtx.restore();

}

各単語を異なるフォントにする必要がある場合は、各単語を定義するオブジェクトの配列 myWords.push( [x:,y:,font:,text:] ) を作成できます。次に、各単語オブジェクトを上記のような関数にフィードします。

そうすれば、単語ごとに高価な html キャンバスを作成する必要がなくなります。

于 2013-11-11T16:49:28.593 に答える