HTML5画布循环上的文本

HTML5画布循环上的文本,html,loops,text,canvas,Html,Loops,Text,Canvas,我这里的代码水平显示了一周中的几天。如何使其水平显示在for循环中,同时考虑画布的大小?(本例中画布的大小为600) 以下是一种方法: // put week names in an array var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], gap = 5, // gap between the names x = 0

我这里的代码水平显示了一周中的几天。如何使其水平显示在for循环中,同时考虑画布的大小?(本例中画布的大小为600)


以下是一种方法:

// 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);
}
//将周名称放入数组中
风险值天数=['星期一'、'星期二'、'星期三'、'星期四',
“星期五”、“星期六”、“星期日”],
间隙=5,//名称之间的间隙
x=0,//用于图形文本
w=0,//用于测量总宽度
i=0;//通用计数器
context.fillStyle=“#5D6C7B”;
context.font=“12px无衬线”;
//计算总宽度,包括间隙
对于(;i
只需记住重置比例或使用它绘制与文本相关的其他元素。您可以做的另一件事是将计算出的位置存储到另一个数组中,以便您可以将其与垂直线等一起使用

另一种方法是,如果所有文本都有空间,则只计算文本的总宽度(不使用间距值),然后从画布宽度中减去它,除以6得到平均间距值,然后用于绘制循环。

你所说的“for循环”指的是什么?动画?请描述您需要的更好:)
// 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);
}