【问题标题】:Text on HTML5 Canvas loopHTML5 Canvas 循环上的文本
【发布时间】:2014-04-16 09:20:44
【问题描述】:

我这里有水平显示星期几的代码。我怎样才能使它水平显示在 for 循环 中,同时还要考虑到画布的大小? (本例中画布大小为600)

canvasObj1 = document.getElementById('myCanvas1');
context = canvasObj1.getContext('2d');

context.fillStyle = "#5D6C7B"; 
context.font = "12px sans-serif"; 
context.fillText("Monday", 10, 225); 
context.fillText("Tuesday", 70, 225); 
context.fillText("Wednesday", 130, 225); 
context.fillText("Thursday", 210, 225); 
context.fillText("Friday", 275, 225); 
context.fillText("Saturday", 330, 225); 
context.fillText("Sunday", 400, 225);

【问题讨论】:

  • “在 for 循环中”是什么意思——动画?请描述你需要更好的:)

标签: html loops text canvas


【解决方案1】:

这是您可以做到的一种方法:

Online demo

// put week names in an array
var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
            'Friday', 'Saturday', 'Sunday'],
    gap = 5,  // gap between the names
    x = 0,    // for drawing text
    w = 0,    // for measuring total width
    i = 0;    // generic counter

context.fillStyle = "#5D6C7B";
context.font = "12px sans-serif";

// calc total width incl. gaps
for (; i < days.length; i++) {
    w += (context.measureText(days[i]).width + gap);
}

// fine adjust width removing last gap and adding a couple of pixels for space
w = w - gap + 2;

// adjust scale
context.scale(canvas.width / w, 1);

// draw the texts
for (i = 0; i < days.length; i++) {
    context.fillText(days[i], x, 225);
    x += (context.measureText(days[i]).width + gap);
}

只需记住重置比例或使用它来绘制与文本相关的其他元素。您可以做的另一件事是将计算出的位置存储到另一个数组中,以便您可以将其与垂直线等一起使用。

如果所有文本都有空间,另一种方法是仅计算文本的总宽度(不使用间隙值),然后从画布宽度中减去它,除以 6 以获得平均间隙值然后你可以使用绘图循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2018-05-10
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    相关资源
    最近更新 更多