iT邦幫忙

0

(已解決!超級感謝)救救js初學者!!Uncaught TypeError: Cannot read properties of null (reading 'clearRect')怎麼辦

  • 分享至 

  • xImage
class Game {
    constructor() {
        this.canvas = document.getElementById("gameCanvas");
        this.context = document.getElementById("2d");
        this.myName = "destiny";
        const game = this;
        const socket = io("http://127.0.0.1:4000", { transports: ['websocket'] });

        socket.on("clientsCount", function(num) {

            console.log("成功連上的人數", num);

        });
        

        socket.on("move all", function(a) {

            // 這邊就會出現問題Uncaught TypeError: Cannot read properties of null (reading 'clearRect')
            //其他地方都是正常運作的
            
            game.context.clearRect(0, 0, game.canvas.width, game.canvas.height);
            const r = 10;
            game.context.beginPath();
            game.context.arc(a.x, a.y, r, 0, 2 * Math.PI);
            game.context.fillStyle = "green";
            game.context.fill();
        });
        
        this.canvas.addEventListener("mousemove", function(e) {
            console.log("mouse on", "x:", e.clientX, "y:", e.clientY);

            
            socket.emit("mouse move go", {
                x: e.clientX,
                y: e.clientY,
                name: game.myName
            });
        });
    };
};
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
淺水員
iT邦大師 6 級 ‧ 2022-04-14 23:18:29
最佳解答
this.context = this.canvas.getContext('2d');

我要發表回答

立即登入回答