Masth0 / ScratchCard

ScratchCard is a js lib to simulated a scratchcard in browser with html5 and canvas.
MIT License
153 stars 49 forks source link

Cannot append Canvas in Vanilla JS Setup (WordPress Website) #53

Closed TONYCRE8 closed 6 months ago

TONYCRE8 commented 6 months ago

I'm currently running a vanilla JS setup (WordPress website, importing Babel-Core and ScratchCard.js in order to use this script), and I've currently hit a similar wall to #44 , however unlike their situation I cannot get my scratchcard to load at all. It responds with the error:

Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
    at ScratchCard.generateCanvas (ScratchCard.ts:210:22)
    at new ScratchCard (ScratchCard.ts:60:10)
    at myscript.js

It seems that the offending function is all to do with generating a canvas, not being able to append anything to the canvas. Unsure of why this is creating so much of an issue. I believe I've imported all of my files properly too:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.26.3/browser.min.js?ver=11:10:34" id="babel-core-js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/scratchcard-js@1.5.5/build/scratchcard.min.js?ver=11:10:34" id="scratchcard-js"></script>
<script type="module" src="https://my.site/wp-content/themes/my-theme/js/myscript.js?ver=11:10:34"></script>

The code in myscript.js is the following:

import 'https://cdn.jsdelivr.net/npm/scratchcard-js@1.5.5/build/scratchcard.js'; 

/* Scratchcard JS */
const scContainer = document.getElementById('js--sc-container');
const sc = new ScratchCard('#js--sc--container', {
    scratchType: SCRATCH_TYPE.CIRCLE,
    containerWidth: scContainer.offsetWidth,
    containerHeight: scContainer.offsetHeight,
    imageForwardSrc: 'https://geek.design/wp-content/uploads/2024/03/gluttony-scratchcard-front.png',
    imageBackgroundSrc: 'https://geek.design/wp-content/uploads/2024/03/gluttony-scratchcard-back.png',
    clearZoneRadius: 50,
    nPoints: 30,
    pointSize: 10,
    callback: function () {
        console.log('Scratch complete!');
    }
});
sc.init().then(() => {
    sc.canvas.addEventListener('scratch.move', function () {
        console.log('Scratch move!');
    });
}).catch((error) => {
    console.error(error);
});

Any and all help is greatly appreciated.