Я хочу раскрасить текст с помощью JavaScript - PullRequest
0 голосов
/ 19 ноября 2018

Хорошо, я хочу переделать матричный дождь с помощью Javascript, и все прошло хорошо (это моя первая «программа»), но я хочу изменить первый символ в «дожде», чтобы он начинался как белый и переходный на зеленый, затем исчезает на черный. Теперь я правильно выполнил последние две части, я просто не могу сделать первую часть. (белый текст).

Мне нужно, чтобы главный ** символ был белым. так что персонаж, который ведет «дождь», должен быть постоянно белым (я не уверен, что это возможно). например: if (drop [i] == 1), 1 - это первая строка на экране, и здесь мне нужно изменить значение, чтобы, если загорающийся символ находился в самом низу дождь становится белым, а затем, когда загорается следующий, становится зеленым, а после - белым (сверху вниз).

Это ожидаемый результат: Требуемый результат

вот полный код:

var c = document.getElementById("c");
var ctx = c.getContext("2d");

//making the canvas full screen
c.height = window.innerHeight;
c.width = window.innerWidth;

var chinese = "ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘヲイクコソチトノフヤヨルレロン012345789:・.\"=*+-<>";
//converting the string into an array of single characters
chinese = chinese.split("");

var font_size = 12;
var columns = c.width / font_size; //number of columns for the rain
//an array of drops - one per column
var drops = [];
//x below is the x coordinate
//1 = y co-ordinate of the drop(same for every drop initially)
for (var x = 0; x < columns; x++)
  drops[x] = 1;
//drawing the characters

function draw() {
  //Black BG for the canvas
  //translucent BG to show trail
  ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
  ctx.fillRect(0, 0, c.width, c.height);
  // Create gradient
  ctx.fillStyle = "#0F0" //green text
  ctx.font = font_size + "px arial";
  //looping over drops
  for (var i = 0; i < drops.length; i++) {
    //a random chinese character to print
    var text = chinese[Math.floor(Math.random() * chinese.length)];
    //x = i*font_size, y = value of drops[i]*font_size
    ctx.fillText(text, i * font_size, drops[i] * font_size);

    //sending the drop back to the top randomly after it has crossed the screen
    //adding a randomness to the reset to make the drops scattered on the Y axis

    if (drops[i] * font_size > c.height && Math.random() > 0.975)
      drops[i] = 0;

    //incrementing Y coordinate
    drops[i]++;
  }
}

setInterval(draw, 95);
* {
  margin: 0;
  padding: 0;
}

body {
  background: black
}

canvas {
  display: block
}
<canvas id="c"></canvas>

Код написан с большой помощью, поэтому я не могу понять некоторые вещи (я думаю, что я понимаю его по большей части).

1 Ответ

0 голосов
/ 20 ноября 2018

Вот и ты, приятель, просто настроил JS для этого.Я просто сохранил сгенерированный текст так, чтобы он рисовал новый сгенерированный текст белым, затем перерисовывал предыдущий текст зеленым цветом в пространстве над ним, а затем, наконец, заменял предыдущий текст новым текстом.

var c = document.getElementById("c");
var ctx = c.getContext("2d");

//making the canvas full screen
c.height = window.innerHeight;
c.width = window.innerWidth;

var chinese = "ハミヒーウシナモニサワツオリアホテマケメエカキムユラセネスタヌヘヲイクコソチトノフヤヨルレロン012345789:・.\"=*+-<>";
//converting the string into an array of single characters
chinese = chinese.split("");

var font_size = 12;
var columns = c.width / font_size; //number of columns for the rain
//an array of drops - one per column
var drops = [];
//x below is the x coordinate
//1 = y co-ordinate of the drop(same for every drop initially)
for (var x = 0; x < columns; x++)
  drops[x] = 1;

//Hold text for next redraw
var previousText = [];
 
//drawing the characters
function draw() {
  //Black BG for the canvas
  //translucent BG to show trail
  ctx.fillStyle = "rgba(0, 0, 0, 0.05)";
  ctx.fillRect(0, 0, c.width, c.height);
  
  ctx.font = font_size + "px arial";
  
  //looping over drops
  for (var i = 0; i < drops.length; i++) {

    //a random chinese character to print
    var text = chinese[Math.floor(Math.random() * chinese.length)];

    //Draw in white
    ctx.fillStyle = "#FFF";
    //x = i*font_size, y = value of drops[i]*font_size
    ctx.fillText(text, i * font_size, drops[i] * font_size);

    //Draw in green
    ctx.fillStyle ="#0F0";
    ctx.fillText(previousText[i], i * font_size, (drops[i] - 1) * font_size);
    previousText[i] = text;


    //sending the drop back to the top randomly after it has crossed the screen
    //adding a randomness to the reset to make the drops scattered on the Y axis

    if (drops[i] * font_size > c.height && Math.random() > 0.975)
      drops[i] = 0;

    //incrementing Y coordinate
    drops[i]++;
  }
}

setInterval(draw, 95);
* {
  margin: 0;
  padding: 0;
}

body {
  background: black
}

canvas {
  display: block
}
<canvas id="c"></canvas>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...