在HTML5画布上单击“事件侦听器” [英] Click Event Listener on HTML5 canvas

查看:85
本文介绍了在HTML5画布上单击“事件侦听器”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按照建议写完整的代码,但似乎没什么意思。网格是我的2D数组,其中包含单词数组的所有单词以及以空方块表示的随机字母。但是代码不起作用。无法调试。需要帮助。谢谢。

Wrote the entire code as suggested but doesn't seem to word. grid is my 2d array containing all the words of 'words' array plus random letters in empty squares. But code doesn't work. Unable to debug. Needed help.Thanks in advance.

function game(grid){
var words =['HELLO', 'CYCLE','APPLE','COOK', 'OPERA','COURT','HOUSE','NEWEST'];
var canvas = document.getElementById("canvas1");
var ctx1 = canvas.getContext("2d");
var $canvas = $("#canvas1");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
ctx1.font = "14px verdana";

$results = $("#results");
$heading = $("#heading");
var rowCount = 15;
var rowHeight = 30;
var colCount = 15;
var colWidth = 30;


// drag related variables
var startX, startY, mouseX, mouseY;
var isDown = false;


// listen for mouse events on the canvas
$("#canvas1").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas2").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas3").mouseout(function (e) {
handleMouseOut(e);
});

// draw the puzzle grid on the canvas
drawRect();

//draw lettered grid
function drawRect() {
ctx1.clearRect(0, 0, canvas.width, canvas.height);
for (var j = 0; j < rowCount; j++) {
    for (var i = 0; i < colCount; i++) {
        ctx1.rect(i * colWidth, j * rowHeight, colWidth, rowHeight);
        ctx1.stroke();
        ctx1.fillText(grid[i][j].toUpperCase(), i * colWidth + 5, j * (rowHeight) +   20);
    }
}
}
// set the starting X/Y of the drag on mousedown
function handleMouseDown(e) {

// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();

startX = parseInt(e.clientX - offsetX);
startY = parseInt(e.clientY - offsetY);

// redraw the puzzle grid on the canvas
drawRect();

// start the drag
isDown = true;
}

// set the ending X/Y of the drag on mouseup
function handleMouseUp(e) {

// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();

// set the ending X/Y
mouseX = parseInt(e.clientX - offsetX);
mouseY = parseInt(e.clientY - offsetY);

// done with the drag
isDown = false;

// check if the drag-selected word is part to the puzzle
checkForWord();
}
// cancel the drag if the mouse exits the canvas
function handleMouseOut(e) {
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// moved out of the canvas, stop the drag
isDown = false;
}


function checkForWord() {

// get the starting & ending grid-cell
// that the user dragged across
var startCol = parseInt(startX / colWidth);
var startRow = parseInt(startY / rowHeight);

var lastCol = parseInt(mouseX / colWidth);
var lastRow = parseInt(mouseY / rowHeight);

// get the word that the user dragged across
// by adding the letters from the starting cell
// to the ending cell
var word = [];;
var length = Math.max(Math.abs(startCol - lastCol) + 1, Math.abs(startRow - lastRow) +      1);
var dx = 0;
var dy = 0;
var x = startCol;
var y = startRow;
if (lastCol > startCol) {
    dx = 1;
}
if (lastCol < startCol) {
    dx = -1;
}
if (lastRow > startRow) {
    dy = 1;
}
if (lastRow < startRow) {
    dy = -1;
}i=0;
while (length > 0) {
    // add the letter in this grid-cell to the word
    word[i]= grid[y][x];
    // highlight the squares that the user selected
    ctx1.save();
    ctx1.fillStyle = "red";
    ctx1.globalAlpha = 0.25;
    ctx1.globalCompositeOperation = "destination-over";
    ctx1.fillRect((x) * colWidth + 2, (y) * rowHeight + 2, colWidth - 4, rowHeight -  4);
    ctx1.restore();
    // increment x/y/length for the next letter
    i++;
    x += dx;
    y += dy;
    length--;
}

// reverse the word if dragged backwards
/*if (dx < 0 || dy < 0) {
    word.split('').reverse().join('');
}*/

// test if the word is a solution word assuming it's spelled frontwards
for(var index=0;index < words.length;i++){
   if(word === words[index])
     var found =1;  

}
if (found === 1){
$results.text("You just found: " + words[index]);}

else 
    {  
        $results.text("Sorry...Try Again.");
    }

}}


推荐答案

[根据提问者的新信息更新的答案]

要在单词搜索难题中拖动选择单词,您需要这些功能:

To drag-select words in a word-search puzzle you need these capabilities:


  • 定义网格和每个网格正方形内的字母。

  • 绘制网格正方形,里面有关联的字母。

  • 监听鼠标按下事件

  • 在鼠标按下时开始拖动操作(保存开始的X / Y鼠标位置)

  • 在mouseup上结束拖动操作(保存结束的X / Y鼠标位置)

  • 同样在mouseup上,检查两次开始之间的字母正​​方形&鼠标的结尾位置会拼写拼图中剩余的单词之一

  • 如果选择了正确的拼图单词,请将其从拼图单词列表中删除

  • Define the grid and the letters inside each grid-square.
  • Draw the grid-squares with the associated letters inside.
  • Listen for mousedown events
  • On mousedown begin the drag operation (save the starting X/Y mouse position)
  • On mouseup end the drag operation (save the ending X/Y mouse position)
  • Also on mouseup, check if the letter-squares between starting & ending mouse positions spell one of the remaining words in the puzzle
  • If a correct puzzle word was selected, remove it from the list of puzzle words

带注释的代码和演示: http://jsfiddle.net / m1erickson / Ud7R3 /

Annotated code and a Demo: http://jsfiddle.net/m1erickson/Ud7R3/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>
<script>
$(function(){

    // canvas related variables
    var canvas=document.getElementById("canvas");
    var ctx1=canvas.getContext("2d");
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var scrollX=$canvas.scrollLeft();
    var scrollY=$canvas.scrollTop();
    ctx1.font="14px verdana";

    // puzzle related variables
    $results=$("#results");
    $puzzle=$("#puzzle");
    var rowCount=7;
    var rowHeight=40;
    var colCount=7;
    var colWidth=40;
    var puzzle="Popcorn tastes good with butter";
    var words=puzzle.toLowerCase().split(' ');
    var letters=['g','b','s','i','c','e','n','o','b','u','w','v','r','d','o','k','i','t','o','n','d','d','t','m','c','t','a','a','h','a','p','y','s','e','c','k','o','z','b','z','i','r','p','t','a','s','t','e','s'];
    $puzzle.text("Find: "+puzzle);


    // drag related variables
    var startX,startY,mouseX,mouseY;
    var isDown=false;

    // listen for mouse events on the canvas
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});

    // draw the puzzle grid on the canvas
    drawRect();


    // draw lettered grid squares
    function drawRect(){
        ctx1.clearRect(0,0,canvas.width,canvas.height);
        for(var j=0;j<rowCount;j++){
            var letterRow=[];
            for(var i=0; i<colCount ;i++){
                ctx1.rect(i*colWidth,j*rowHeight,colWidth,rowHeight);
                ctx1.stroke();      
                ctx1.fillText(letters[j*colCount+i].toUpperCase(),i*colWidth+15,j*(rowHeight)+25);
            }
        }
    }

    // set the starting X/Y of the drag on mousedown
    function handleMouseDown(e){

      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();

      startX=parseInt(e.clientX-offsetX);
      startY=parseInt(e.clientY-offsetY);

      // redraw the puzzle grid on the canvas
      drawRect();

      // start the drag
      isDown=true;
    }

    // set the ending X/Y of the drag on mouseup
    function handleMouseUp(e){

      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();

      // set the ending X/Y
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);

      // done with the drag
      isDown=false;

      // check if the drag-selected word is part to the puzzle
      checkForWord();


    }

    // cancel the drag if the mouse exits the canvas
    function handleMouseOut(e){
      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();
      // moved out of the canvas, stop the drag
      isDown=false;
    }

    function checkForWord(){

        // get the starting & ending grid-cell
        // that the user dragged across
        var startCol=parseInt(startX/colWidth);
        var startRow=parseInt(startY/rowHeight);
        var lastCol=parseInt(mouseX/colWidth);
        var lastRow=parseInt(mouseY/rowHeight);

        // get the word that the user dragged across
        // by adding the letters from the starting cell
        // to the ending cell
        var word="";
        var length=Math.max(Math.abs(startCol-lastCol)+1,Math.abs(startRow-lastRow)+1);
        var dx=0;
        var dy=0;
        var x=startCol;
        var y=startRow;
        if(lastCol>startCol){dx=1;}
        if(lastCol<startCol){dx=-1;}
        if(lastRow>startRow){dy=1;}
        if(lastRow<startRow){dy=-1;}
        while(length>0){
            // add the letter in this grid-cell to the word
            word+=letters[y*colCount+x];
            // highlight the squares that the user selected
            ctx1.save();
            ctx1.fillStyle="red";
            ctx1.globalAlpha=0.25;
            ctx1.globalCompositeOperation="destination-over";
            ctx1.fillRect((x)*colWidth+2,(y)*rowHeight+2,colWidth-4,rowHeight-4);
            ctx1.restore();
            // increment x/y/length for the next letter
            x+=dx;
            y+=dy;
            length--;
        }

        // reverse the word if dragged backwards
        if(dx<0 || dy<0){ word.split('').reverse().join(''); }

        // test if the word is a solution word assuming it's spelled frontwards
        var frontwards=words.indexOf(word.toLowerCase());

        // test if the word is a solution word assuming it's spelled backwards
        var backwards=words.indexOf(stringBackwards(word).toLowerCase());

        // if the selected word matches a puzzle word
        // tell the user they found the word an remove the word from the puzzle
        // if the selected word doesn't match any remaining puzzle word
        // tell the user to try again
        if(frontwards>=0 || backwards>=0){
            var index=Math.max(frontwards,backwards);
            $results.text("You just found: "+words[index]);
            words.splice(index,1);
            if(words.length>0){
                var remainingWords="Find:"
                for(var i=0;i<words.length;i++){
                    remainingWords+=" "+words[i];
                }
                $puzzle.text(remainingWords);
            }else{
                $puzzle.text("Congratulations...");
                $results.text("You found all the words in the puzzle!");    
            }

        }else{
            if(words.length>0){
                $results.text("Sorry...Try Again.");
            }
        }
    }

    function stringBackwards(s){
        return(s.split('').reverse().join(''));
    }

}); // end $(function(){});
</script>
</head>
<body>
    <h3 id="puzzle">Find: Popcorn tastes good with butter</h3>
    <h4 id="results">Drag through the lettered squares</h4>
    <canvas id="canvas" width=350 height=350></canvas>
</body>
</html>

这篇关于在HTML5画布上单击“事件侦听器”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆