文字の色を徐々に変えるJavaScript

文字の色を徐々に変えるJavaScript


// 機能部分
function setValues() {
 R_dif = R_to - R_from;
 G_dif = G_to - G_from;
 B_dif = B_to - B_from;
 
 R_10 = R_from;
 B_10 = B_from;
 G_10 = G_from;
 
 R_step = Math.round (R_dif / steps);
 G_step = Math.round (G_dif / steps);
 B_step = Math.round (B_dif / steps);
}

function tidyValue (val) {
 if (!val) { return 0; } 
 if (val < 0) { return 0; }
 if (val > 255) { return 255; }
 return val;
}

function convertTo16(str) {
 if (str >= 0 && str<=255) {
  if (str <=15) { return '0' + str.toString(16) }
  return str.toString(16);
 }
 return '00';
}

function dissolveText() {
 if (!obj) { clearInterval(colour_timer); return false; };
 
 if (obj.length) {
  for (i=0; i<=obj.length-1; i++) {
   colourObj(obj[i])
  }
 }
 else { colorObj(obj) }

 function colourObj(j) {
  j.style.color = '#' + convertTo16(R_10) + convertTo16(G_10) + convertTo16(B_10);
 }
 R_10 = calcColour(R_10, R_step, R_to);
 G_10 = calcColour(G_10, G_step, G_to);
 B_10 = calcColour(B_10, B_step, B_to);
 if (R_10 == R_to && G_10 == G_to && B_10 == B_to) { clearInterval(colour_timer) }
}

function calcColour(C_10, C_step, C_to) {
 if (C_10 == C_to || C_step == 0) { return C_to }
 if (C_step < 0) {
  if (C_10 > C_to) {
   if (C_10 + C_step >= C_to) { return C_10 + C_step; }
   if (C_10 + C_step <= C_to) { return C_to }
  }
 }
 if (C_step > 0) {
  if (C_10 < C_to) {
  if (C_10 + C_step <= C_to) { return C_10 + C_step; }
  if (C_10 + C_step >= C_to) { return C_to }
  }
 }
}

function startColourText (R1,R2,G1,G2,B1,B2,STEPS,INTERVAL,OBJECT) {
 obj = OBJECT;
 R_from = tidyValue(R1);
 G_from = tidyValue(G1);
 B_from = tidyValue(B1);
 R_to = tidyValue(R2);
 G_to = tidyValue(G2);
 B_to = tidyValue(B2);
 steps = tidyValue(STEPS) || 1;
 if (!INTERVAL || INTERVAL <0) { INTERVAL = 100 }

 setValues();

 colour_timer = setInterval('dissolveText()', INTERVAL);
}
// 機能部分ここまで 

// 実行部 
startColourText(255,0,244,0,0,257,16,150,document.body);
 
// 説明
引数は順に、
[Rの開始値(0-255、以下同)]
[Rの終了値]
[Gの開始値]
[Gの終了値]
[Bの開始値]
[Bの終了値]
[ステップ数(1-255)]
[1ステップの長さ(ミリ秒)]
[色を変えたいオブジェクト(style.color属性を持つもの)]
 

 


Leave a Reply