I'm learning JavaScript and tried to do a simple function, but get this error while attempting to run:
TypeError: drCtx is null
html:
<body onload="init()">
<div style="min-width: 400px; display: inline-block;"></div>
<canvas id="test" width="1000" height="800"></canvas>
</body>
js:
var width, height;
var drCtx;
var charsize =15;
var chars = ["0","1"]
var charArray;
var c,r;
//Initialze canvas
function init(){
var canvasElement = document.getElementById("test");
drCtx = canvasElement.getContext("2D");
width = canvasElement.width;
height = canvasElement.height;
c = parseInt(Math.ceil(width / charsize));
r = parseInt(Math.ceil(height / charsize));
charArray = new Array(c);
for(var i=0; i<c;i++)
{
charArray[i] = new Array(r);
for(var j =0; j<r;j++)
{
var rIndex = parseInt(randomIntFromInterval(0, chars.length-1));
charArray[i][j] = chars[rIndex];
}
}
console.log(charArray);
renderDR();
}
function renderDR(){
drCtx.fillStyle = "#000000";
drCtx.beginPath();
drCtx.fillRect(0,0,width,height);
drCtx.fill();
drCtx.fillStyle = "#FFFFFF"
for(var i=0; i<c;i++)
{
for(var j =0; j<r;j++)
{
var x = i*charsize;
var y = j*charsize;
drCtx.fillText(charArray[i][j],x,y);
}
}
}
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
My init() fucntion doesn't have this problem and doesn't have return. I don't know what went wrong, any help is appreciated!
Change this line:
.getContext("2D")
To:
.getContext("2d")