最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - FillText not working - Stack Overflow

programmeradmin7浏览0评论

I'm unable to get the text on the canvas. What am I doing wrong here ?

JSFiddle - /

var el = document.getElementById('mycanvas');
var context = el.getContext('2d');

context.globalAlpha = 0.95;
context.beginPath();
context.rect(0, 0, el.width, el.height);
context.fillStyle = "#435a6b";
context.fillText('Hello World',0,0);
context.fill();

I'm unable to get the text on the canvas. What am I doing wrong here ?

JSFiddle - http://jsfiddle/qHpt6/

var el = document.getElementById('mycanvas');
var context = el.getContext('2d');

context.globalAlpha = 0.95;
context.beginPath();
context.rect(0, 0, el.width, el.height);
context.fillStyle = "#435a6b";
context.fillText('Hello World',0,0);
context.fill();
Share Improve this question asked Nov 7, 2013 at 14:30 user1184100user1184100 6,89430 gold badges84 silver badges122 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

You're trying to draw 40 point text into a little teeny box. Make the box bigger or the text a lot smaller.

You're also drawing the text at the upper left corner of the box. The text goes up from the baseline.

If you change the box size to something like 350 wide and 250 high, and change the code to

context.fillText("Hello World", 0, 200);

then you'll see the text.

Forked and fixed fiddle.

There is multiple issues:

  1. The canvas is too small too correctly draw the text.
  2. The text has the same fillStyle as the rectangle, so one cannot see it.
  3. You draw the rectangle after the text, so the text is covered.

You may try this code:

    context.globalAlpha = 0.95;
    context.rect(0, 0, el.width, el.height);
    context.fillStyle = "#435a6b";
    context.fill();
    
    context.font = 'italic 40pt Calibri';
    context.fillStyle = "black";
    context.fillText('Hello World',50,50);

http://jsfiddle/qHpt6/

发布评论

评论列表(0)

  1. 暂无评论