简体   繁体   中英

clicking text in an html5 canvas

How do I program the canvas to set go = true; in regular js when you click on the word "play" on the canvas? if go = true, it starts the game. this code prints play onto the canvas. . this is my js code:

var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 336;


    var go = false;

    var reset = function() {
        //reset function
    };

    var main = function () {
    //main function
    };

    var menu = function () {

        ctx.clearRect (0 , 0 , canvas.width , canvas.height);

        ctx.fillStyle = "rgb(250, 250, 250)";
        ctx.font = "24px Helvetica";
        ctx.textAlign = "left";
        ctx.textBaseline = "middle";
        ctx.fillText("play", 32, 32);
    }

    if (go == true) {
        reset();
        var then = Date.now();
        setInterval(main, 1);
    }
    else {
        menu();
    }

The first thing you can adjust is these parts as using a setInterval with 1 ms will do not good:

var main = function () {
    //main function

   if (go === true) setTimeout(main, 16);
   //use requestAnimationFrame(main) instead, 
};

To check for click on the button you can do something like this:

Demo:
http://jsfiddle.net/AbdiasSoftware/n8Hsd/

Define a rectangle where text would be:

rect = {
    x: 32,
    y: 32,
    w: 70,
    h: 30
};
//this is not proper way to calculate text boundary,
//but for demo's sake.
ctx.fillText("play", rect.x, rect.y + 16);

Then listen to canvas' click event and check if clicked position is inside that rectangle:

canvas.addEventListener('click', checkStart, false);

function checkStart(e) {
    var p = getMousePos(e);

    if (p.x >= rect.x && p.x <= rect.x + rect.w &&
        p.y >= rect.y && p.y <= rect.y + rect.h) {

        go = !go;
        if (go === true) {
            main();
        } else {
            menu();
        }
    }
}

The mouse position can be calculated like this:

function getMousePos(e) {
    var r = canvas.getBoundingClientRect();
    return {
        x: e.clientX - r.left,
        y: e.clientY - r.top
    };
}

You just need to check whether the mouse in inside the text's bounding box when the canvas is clicked. If the mouse's position is inside the text's bounding box when clicking, then the text is being clicked and you should set go to true .

Something like this will help.

var bbox = {x:10,y:10, w:100, h:100};
if(mouseX >= bbox.x && mouseY >= bbox.y && mouseX <= bbox.x + bbox.w && mouseY <= bbox.y + bbox.h){
    go = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM