Home > Enterprise >  document.getElementById() is null react
document.getElementById() is null react

Time:05-23

I'm trying to get the canvas element using document.getElementById('canvas') in my code but it doesn't work. Please help! I spend this week searching for a solution but I didn't find anything.

import React, { useEffect } from 'react'
import * as tf from '@tensorflow/tfjs'

const Analysis =  () => {

const canvas = document.getElementById('canvas')
console.log(canvas)
const ctx = canvas.getContext('2d').data
const img = new Image();
img.src = "Images/bg.jpg"
img.onload = function () {
        ctx.drawImage(img,0,0,256,256)
        data = context.getImageData(0,0,256,256)
        var input = [];
        for (var i = 0; i < data.length; i  = 4) {
            input.push(data[i   2] / 255);
        }
        predict(ctx)    
}
    var predict =  async function (input) {
        
    await tf.loadLayersModel('model.json').then(function(model){
        
        window.model= model
    });
        if (window.model) {
            window.model.predict(Input)
                .then(function (scores) {
                    scores = scores[0];
                    console.log(scores
                        .indexOf(Math.max(...scores)));
                });
                console.log('processing...')
        } else {
      
            // The model takes a bit to load, 
            // if we are too fast, wait
            setTimeout(function () { predict(input) }, 50);
        }
    }
return ( 
        <canvas id='canvas' width='1000' ></canvas>
     );
}
 
export default Analysis;

CodePudding user response:

Its cause you're trying to get the element before the page loads, wrap it in useEffect:

useEffect(() => {
const canvas = document.getElementById('canvas')
console.log(canvas)
  }, []);

also its suggested to use useRef instead of document.getElementById, check this answer to know why

  • Related