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

时间:2015-04-24 01:37:13

标签: javascript html5 canvas event-listener

我试图让我的图像跟随我的鼠标。我使用了大学的讲座指南来创建此代码,它看起来与我见过的所有代码完全相同,但我在Chrome开发人员工具中遇到错误: 未捕获的TypeError: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>

3 个答案:

答案 0 :(得分:3)

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

thisCanvas现在有字符串值white

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

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

答案 1 :(得分:1)

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

应该是

    var thisCanvas = document.getElementById("myCanvas")

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

答案 2 :(得分:1)

问题在于:

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

thisCanvas没有对&lt; canvas&gt;的引用元件。相反,由于链式分配,它已绑定到'white'

您可能需要以下内容:

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