Search code examples
javascripthtmlcsscodepen

How do you clear canvases in javascript?


https://codepen.io/MabelJane/pen/ROjONN

Hello, I have been creating a green screen algorithm on code pen which I have put a link to above. Most of it seems to be working except from the JavaScript that is supposed to clear the canvases. I think it will probably be something quite simple but I can't work it out. I put the code that I think is what doesn't work below. Thank you 🙂

function clear() {
    var fgCanvas = document.getElementById("can1");
    var bgCanvas = document.getElementById("can2");
    var fgContext = fgCanvas.getContext("2d");
    var bgContext = bgCanvas.getContext("2d");
    fgContext.clearRect(0, 0, fgCanvas.width, fgCanvas.height);
    bgContext.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
}

Solution

  • It seems that Javascript doesn't like the function name you're using - clear() - thus the function won't ever be called. Try renaming the function to clearIt() or something like that. Apart from that your code for cleaning the canvases is correct.