我正在尝试从Firestore数据库中获取数据,并使用该数据创建画布。我的目标是加载一组图像和地图以返回几个画布。 我不断收到此错误:
Uncaught (in promise) TypeError: Cannot read property 'getContext' of null
我尝试使用setTimeout()来延迟速度以帮助更快地加载数据,但是似乎没有任何效果。
var gImgObj;
var gMeme = [];
var gCtx;
var canvas;
function memeDivGet(theId){
setTimeout(function(){
db.collection("memeInfo").where("creator", "==", theId)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
db.collection("memeInfo").doc(doc.id).collection("MIMG")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
//alert(doc.data())
// alert("here")
console.log(doc.data().Coordinates[0].fontSize)
gMeme.push(doc.data().BaseIMG)
for (var i = 0; i < doc.data().Coordinates.length; i++) {
// alert("here" + i)
gMeme.push({
line: "line",
size: doc.data().Coordinates[i].fontSize,
align: doc.data().Coordinates[i].align,
color: doc.data().Coordinates[i].color, // in color picker, if choosing color from platte notice it stays "solid".
fontFamily: doc.data().Coordinates[i].fontStyle,
lineWidth: 2, // outline width
x: doc.data().Coordinates[i].xPos,
y: doc.data().Coordinates[i].yPos,
text: doc.data().Text[i]
})
}
//console.log(doc.data().BaseIMG)
initCanvas(doc.data().BaseIMG);
})
})
})
})
},1500)
}
function initCanvas(link) {
var canvas = document.querySelector('#canvasImage');
gCtx = canvas.getContext('2d');
gImgObj = new Image();
// console.log(link)
//alert(gMeme[0])
gImgObj.src = link;
gImgObj.onload = function () {
canvas.width = gImgObj.width;
canvas.height = gImgObj.height;
drawCanvas();
};
//console.log("HERE4")
}
function drawCanvas() {
//alert(gMeme)
gCtx.drawImage(gImgObj, 0, 0);
for (var i = 0; i < gMeme.length; i++) {
if(i > 1){
drawTxt(gMeme[i]);
}
}
for (var i = 0; i < gMeme.length - 1; i++) {
drawTxt(gMeme[i + 1]);
}
// gMeme.txts.forEach(function (txt) {
// drawTxt(txt);
// });
}
function drawTxt(txt) {
gCtx.font = txt.size + 'px' + ' ' + txt.fontFamily;
gCtx.textAlign = txt.align;
gCtx.fillStyle = txt.color;
gCtx.fillText(txt.text, txt.x, txt.y);
}
我要返回的是一组带有我想要的参数的画布。
以这种方式为代码的这一部分设置了我的数据库:
(fooIds表示由Firebase设置的随机ID)
在每个fooId文档中,都有一个creatorId,它可以帮助计算机查找创建此模因的人。我使用它来查找应该用于该特定创建者帐户的文档。
“ gMeme”是一个包含数据库信息的数组。
“文档”具有BaseIMG(背景图像),内部带有地图的坐标数组(包含大小,颜色,fontFamily和其他参数)以及内部带有字符串的文本数组。有一张附有“文档”的图片。
我知道这很令人困惑,因此,如果您有任何疑问,请在评论部分提问。