HTML5 Canvas 和 JS - 鼠标移动,奇怪的错误

HTML5 Canvas and JS - Mouse Movement, strange error

我想让我的图像跟随我的鼠标。我使用了大学的讲座指南来创建此代码,它看起来与我见过的所有代码都相同,但我在 Chrome 开发人员工具中遇到错误: 未捕获的类型错误:thisCanvas.addEventListener 不是函数

有什么想法吗?我已经盯着这个看了好几个小时了。

<!DOCTYPE html>
<html>
    <head>
        <title> Gravity Game </title>
        <meta charset = "UTF-8">
        <link type = "text/css" rel = "stylesheet" href = "style.css">
    </head>

    <body onLoad="start_game()">
        <header>
            <h1 id = "title1"> Gravity </h1> <h1 id = "title2"> Game </h1>
        </header>

        <ul id = "nav">
            <li class = "inactive"><a href = "about.html"> About </a></li>
            <li id = "active"><a href = "play.html"> Play Game </a></li>
        </ul>

        <canvas id = "myCanvas" width = "1500" height = "500"></canvas>

        <script>
            var thisCanvas = document.getElementById("myCanvas").style.background = 'white';
            var context = myCanvas.getContext("2d");
            var worldX = 100;
            var worldY = 100;

            //Draw a circle
            /*context.beginPath();
            context.arc(95, 50, 40, 0, 2 * Math.PI);
            context.closePath();
            context.fill();*/

            thisCanvas.addEventListener("mousemove",seen_move,false);

            function seen_move(e)
            {
                var bounding_box = thisCanvas.getBoundingClientRect();
                worldX = (e.clientX-bounding_box.left) * (thisCanvas.width/bounding_box.width); 
                worldY = (e.clientY-bounding_box.top) * (thisCanvas.height/bounding_box.height);
            }

            function start_game()
            {
                setInterval(loop_game, 50);
            }

            function loop_game()
            {
                thisCanvas.width = thisCanvas.width;
                update_world(worldX, worldY);
            }

            function update_world(x, y)
            {
                var world_img = new Image();
                world_img.src = "images/world.png";
                context.drawImage(world_img, x, y);
            }



        </script>

    </body>

</html>
var thisCanvas = document.getElementById("myCanvas").style.background = 'white';

thisCanvas 现在具有字符串值 white.

thisCanvas.addEventListener() 基本上就像说 'white'.addEventListener()。因为没有String.prototype.addEventListener这不行。

您需要将 document.getElementById("myCanvas") 分配给 thisCanvas 并且 然后 设置它的背景颜色。

    var thisCanvas = document.getElementById("myCanvas").style.background = 'white';

应该是

    var thisCanvas = document.getElementById("myCanvas")

您正在尝试将 canvas 样式更改方法指定为变量 thisCanvas,而不是指定 canvas 元素本身

问题在于:

var thisCanvas = document.getElementById("myCanvas").style.background = 'white';

thisCanvas 不包含对 元素的引用。相反,由于链式赋值,它绑定到 'white'

你可能想要这样的东西:

 var thisCanvas = document.getElementById("myCanvas");
 thisCanvas.style.background = 'white';