繁体   English   中英

在html5画布中更改字体的问题

[英]Issues with changing font in html5 canvas

我有一小段代码,里面有2个画布和文字。 但我无法更改指定画布的字体大小。

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

在下面的代码我试图改变第二个画布的字体,但它没有得到应用。

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); 
}

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画布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM