【问题标题】:Creating a button on an HTML5 canvas using JavaScript使用 JavaScript 在 HTML5 画布上创建按钮
【发布时间】:2012-04-23 01:27:58
【问题描述】:

我正在尝试编写一个简单的游戏来使用 HTML5 画布和 JavaScript 教授一些基本的威尔士语。

我目前有一个网页,它显示了一个画布,并且在画布上绘制了“开始按钮”,用户将单击该按钮开始游戏。

我现在想向那个按钮添加功能,这样当用户点击它时,游戏的第一关就会显示在画布上。但是,我遇到了一些麻烦,想知道是否有人可以帮助我。

我的 index.html 文件中有以下代码:

在头部的一个隐藏部分,我有:

<section hidden>
<img id="StartButton" src="StartButton.png" alt="Start Button" width="179" height="180" />

<script type="text/javascript">
    /* Create a canvas layer to display text */
    function displayText(textLayer, message){
        var textLayerContext = textLayer.getContext();
        textLayer.clear();
        textLayerContext.font = "18pt Calibri";
        textLayerContext.fillStyle = "black";
        textLayerContext.fillText(message, 10, 10);
    }

    /* Create a canvas layer to display the button */
    window.onload = function(){
        var stage = new Kinetic.Stage({
            container: "container",
            width: 179,
            height: 180
        });
        var buttonLayer = new Kinetic.Layer();
        var textLayer = new Kinetic.Layer();
</script>


</section>

在body onLoad...我调用了函数startGame(),然后body标签内有如下代码:

<body onLoad="startGame()">
    <h1>Home</h1>
    <p1>The purpose of this website is to allow users to learn some basic Welsh by playing the game below. <br /><br /></p1>
    <p2>

    <canvas id="gameCanvas" width="700" height="300" style="border:1px dotted">
    Your browser does not support the canvas element.
    </canvas>

    <script type="text/javascript">
        /* Create the canvas, and add some global variables. */
        var myGameCanvas = document.getElementById("gameCanvas");
        var context = myGameCanvas.getContext("2d");
        var image = new Image();
        var imageSource;
        var imageX;
        var imageY;

        /* Global variables- game elements */
        var currentLevel=1;
        var totalLevels=5;
        var currentScore=0;
        var currentScorePositionX=100;
        var currentScorePositionY=100;


        /* This function starts the game, and calls all of the other functions required to play the game */
        function startGame(){
            drawGameElements();
            drawStartButton(); 
            /* Now need to add an event listener to call drawLevelOneElements() when
                the start button is clicked. */
            myGameCanvas.addEventListener("click", drawLevelOneElements, false);
            //drawLevelOneElements();
            //game_id=setInterval(game_loop, 50);
        }

        /* This function draws the game elements */
        function drawGameElements(){

            /* Draw a line for the 'score bar'. */
            context.moveTo(0, 25);
            context.lineTo(700, 25);
            context.stroke();

            /* Draw current level/ total levels on the left, and current score on the right. */
            context.font = "11pt Calibri"; /* Text font & size */
            context.strokeStyle = "black"; /* Font colour */
            context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
            context.strokeText(currentScore, 650, 15);
        }

        /* This function draws a start button which the user can click to start the game */
        function drawStartButton(){
            image.onload = function(){
                context.drawImage(image, 260.5, 60);
            };
            image.src = "StartButton.png";
            /** Now I need to add an event listener to the area of the canvas on 
                on which the button image is displayed, in order to 'listen' for 
                a click on the button */
            var boundingBox = myGameCanvas.getBoundingClientRect();
            var mouseX = (mouse_event.clientX-boundingBox.left) * (myGameCanvas.width/boundingBox.width);
            var mouseY = (mouse_event.clientY-boundingBox.top) * (myGameCanvas.height/boundingBox.height);
            var pixels = context.getImageData(mouseX, mouseY, 1, 1);

            /** There maybe more than one pixel at this location so use a loop
                to test whether any of the pixels have an alpha value greater than
                0. With pixel data, 3 is alpha, so check data[3] and every fourth
                element in data after that. */
            //for (var i=3; i<pixels.data.length; i+=4;){
                /** If a non- zero alpha is found, stop and return "true"- the click
                    was on a part of the canvas that has colour on it. */
            //  if(pixels.data[i]!=0) return true;
            //}

            /** If the function gets here, then the mouse click wasn't on a painted
                part of the canvas. */
            //return false;
            /**myGameCanvas.getElementById("StartButton").onClick = function(e){
                drawLevelOneElements();
            } */                
        }


        /* This function draws the elements for level 1. */
        function drawLevelOneElements(){
            var context = canvas.getContext("2d");

            /* Draw the images for numbers 1-10.*/
            var image1 = new Image();
            /* Test that this code is being executed */
            context.moveTo(300, 300);
            context.font = "11pt Calibri";
            context.strokeStyle = "black";
            context.strokeText("Testing",300, 300);
            /* End of test */

            image1.onLoad = function(){
                context.drawImage(image1, 50, 50);
                };
            image1.src="1.png";
        }

        /* This function is what will be used to draw the images on the canvas */
        function drawImage(x, y){
            var numberImage = new Image();
            numberImage.src = imageSource;
            context.drawImage(numberImage, x, y);

        }

    </script>
    <br /><br /></p2>
    <p3>Use this paragraph to enter text that provides the user with instructions for how to play the game. <br />
        Update the instructions so that they're appropriate to whatever level the user is currently playing.</p3>
</body>

目前,当我在浏览器中查看页面时,我在画布中显示了一个“开始按钮”,如上所述。我无法解决的是如何让画布在单击开始按钮时调用函数 drawLevelOneElements() ...如果有人能指出正确的方向,我将不胜感激?

提前致谢!

感谢您的回复。我已尝试进行您建议的更改,所以我现在有:

 function startGame(){
            drawGameElements();
            drawStartButton(); 
            /* Now need to add an event listener to call drawLevelOneElements() when
                the start button is clicked. */
            //myGameCanvas.addEventListener("click", drawLevelOneElements, false);
            //drawLevelOneElements();
            //game_id=setInterval(game_loop, 50);
            /*Add event listener to the canvas */
            myGameCanvas.addEventListener('click', function(e){
                console.log('click: ' + e.offsetX + '/' + e.offsetY);
                var buttonHit = collides(StartButton, e.offsetX, e.offsetY);
                if(buttonHit){
                    alert('collision: ' + buttonHit.x + '/' + buttonHit.y);
                } else {
                    console.log('no collision');
                }
            }, false);
        }

但是当我在浏览器中查看页面时,我仍然只显示带有开始按钮图像的画布,并且没有任何功能......即点击不会做任何事情......

有什么建议吗?

【问题讨论】:

    标签: html5-canvas


    【解决方案1】:

    你必须监听鼠标悬停事件,并且必须比较鼠标的坐标,以确定鼠标是否在按钮(矩形)内

    有一个很好的帖子here,你必须在浏览器控制台中看到点击事件检测。如果你可以去控制台,你可能需要改变

    console.log('碰撞:' + rect.x + '/' + rect.y);

    alert('碰撞:' + rect.x + '/' + rect.y);

    【讨论】:

    • 感谢您的回复-尝试回复它,但它说我的回复太长,所以我编辑了我的原始帖子以包含回复...
    • 你知道如何调试对你有帮助的javascript代码吗?您可以在互联网上搜索您正在使用的浏览器的调试,这将帮助您...
    • 请记住,如果您的消息很长,您可以发送多个,编辑问题进行讨论不是很合适。也试着理解我发送的例子。希望能帮助你解决问题
    • 好的,只是一个快速的...我正在浏览器中查看我的页面,并使用 Firebug 尝试调试它 - 它告诉我 moust_event 未定义。我知道我应该知道我需要在这里做什么,但我就是想不起来——任何提示?
    • 我认为在这个声明中 myGameCanvas.addEventListener("click", drawLevelOneElements, false);你必须把drawLevelOneElements放在像“drawLevelOneElements”这样的双引号中
    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 2012-11-23
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多