0

I have a code with constructor for each letter of the alphabet. so if i say new A (x,y,w,h) I can create a new A which will draw itself on the canvas. Is there a way to automate this process in passing a string to a function which will draw each letter of the string individually? (working with P5.js )

I get the error "characters[i] is not a constructor".

thank you

       
function createword(str) {
    str.toUpperCase();

    var characters = str.split('');
    console.log(characters)
    var space = 0

    for (let i = 0; i < characters.length; i++) {
        word[i] = new characters[i](space, 0, 100, 100)
        space += 100
            //  word.push(characters[i])

    }

    for (let i = 0; i < word.length; i++) {
        word[i].setuplettre()
        word[i].drawlettre()
    }

    console.log(word)
}
xdumaine
  • 10,096
  • 6
  • 62
  • 103
vermar
  • 27
  • 4
  • what are you trying to do with this line? `word[i] = new characters[i](space, 0, 100, 100)`? `characters[i]` is going to be a primitive `string` type, with a single character, not a constructor or a function. – xdumaine Mar 12 '21 at 13:35
  • I am trying to refer to the different letter subclass i have. So if I have the world "hello", it would create a new H, new E, new L, new L, new O. – vermar Mar 12 '21 at 13:38
  • Is there a way to transform the string to refer to the constructor name? – vermar Mar 12 '21 at 13:39
  • 1
    I see - check out the linked question (https://stackoverflow.com/questions/5646279/get-object-class-from-string-name-in-javascript) - it has an answer that will help you. – xdumaine Mar 12 '21 at 13:39
  • Hello ! I have just tried this map method but I think I am not doing right, I goet the same problem ("not a contructor") ' function createword(str) { var classes = { A: new A(0, 0, 100, 100), B: new B(0, 0, 100, 100), }; str.toUpperCase(); var characters = str.split(''); for (let i = 0; i < characters.length; i++) { char = new classes[characters[i]]() char.setuplettre() char.drawlettre() } }' – vermar Mar 12 '21 at 13:52
  • See here -> https://jsfiddle.net/71u0ajvd/ – xdumaine Mar 12 '21 at 13:58

0 Answers0