I have this function type() where I define an array texts and I add some values to it and then I set the local texts array to the state array, so it'll be accessible for other functions as well.
var texts = [];
texts.push("Hello", 20, 20)
this.setState({texts: texts})
And this is the state:
state ={
texts:[]
}
I check with the alert() what's the index of 0 of the array to see if it's working, however it says it's undefined:
alert(this.state.texts[0])
This is my whole function:
type()
{
var canvas = document.getElementById('board'),
ctx = canvas.getContext('2d'),
font = '20px sans-serif',
hasInput = false;
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var texts = [];
texts.push("Hello", 20, 20)
this.setState({texts: texts})
alert(this.state.texts[0])
ctx.font = font
ctx.fillText("rrwerwewewrewrwerwe", 50, 50)
canvas.onclick = function(e) {
if (hasInput) return;
addInput(e.clientX, e.clientY);
}
//Function to dynamically add an input box:
function addInput(x, y) {
var input = document.createElement('input');
input.type = 'text';
input.style.position = 'fixed';
input.style.left = (x - 4) + 'px';
input.style.top = (y - 4) + 'px';
input.onkeydown = handleEnter;
document.body.appendChild(input);
input.focus();
hasInput = true;
}
//Key handler for input box:
function handleEnter(e) {
var keyCode = e.keyCode;
if (keyCode === 13) {
addText(this.value, parseInt(this.style.left, 10), parseInt(this.style.top, 10));
document.body.removeChild(this);
hasInput = false;
}
}
//Draw the text onto canvas:
function addText(text, x, y) {
ctx.position = 'absolute';
ctx.font = font;
ctx.fillText(text, x, y);
}
}