1

JS:

(function(win, doc) {

"use strict";

class Matrix {
  constructor(){
    this.canvas = new Canvas();
  } 
  run(){
    let matrixInterval;
    if(typeof matrixInterval != 'undefined'){
      clearInterval(matrixInterval);
    }
    matrixInterval = setInterval(this.canvas.draw, 33); 
  }
}
class Canvas {
  constructor() {
    this.matrix = document.getElementById('matrix');
    this.width = matrix.width;
    this.height = matrix.height;
    this.ctx = matrix.getContext('2d');
    this.positionsY = Array(300).join(0).split('');
  }

  initialize() {
    this.ctx.fillStyle='rgba(0,0,0,.05)';
    this.ctx.fillRect(0, 0, this.width, this.height);
    this.ctx.fillStyle = '#0F0';
    this.ctx.font = '10pt Georgia';
  }

  draw() {
    this.initialize();
    this.positionsY.map((y, index) => {
      let text = Math.round(Math.random());
      let x = (index * 10) + 10;
      this.ctx.fillText(text, x, y);
      if(y > 100 + Math.random() * 1e4){
        this.positionsY[index] = 0;    
      }else{
        this.positionsY[index] = y + 10;
      }
    });
  }
}

function main () {
  const matrix = new Matrix();
  matrix.run();
}

main();

})(this, document);

HTML:

<canvas id="matrix"></canvas>

Возникает ошибка:

this.initialize is not a function at draw

Вроде вызываю метод initialize() в методе draw() правильно. Думаю ошибка где-то при создании экземляра Canvas в классе Matrix, но не понимаю в чем дело. Весь код запускаю в codepen.

Finskij
  • 33
  • Теряется контекст вот здесь: setInterval(this.canvas.draw, 33); Вы имели в виду setInterval(this.canvas.draw.bind(this.canvas), 33) или что-то в этом роде, например this.draw = this.draw.bind(this) в конструкторе канваса. Подробнее читать здесь: https://ru.stackoverflow.com/questions/535030/%D0%9F%D0%BE%D1%82%D0%B5%D1%80%D1%8F-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%B0-%D0%B2%D1%8B%D0%B7%D0%BE%D0%B2%D0%B0 – Утка Учится Укрываться Jan 07 '18 at 10:50
  • @УткаУчитсяУкрываться спасибо, теперь все работает. – Finskij Jan 07 '18 at 10:56

0 Answers0