2014-03-12 44 views
0

我在此處有代碼顯示水平方向的星期幾。我怎樣才能使它在水平方向上顯示在的循環中,同時也考慮到了畫布的大小? (畫布在這種情況下,大小爲600)HTML5 Canvas循環中的文本

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); 
+0

你是什麼意思的「在for循環」 - 動畫?請描述你需要更好的:) – markE

回答

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得到平均間隔值然後使用draw循環。

+0

謝謝,完美的工作:) – coderdojo