单击HTML5画布上的Event Listener

时间:2014-06-03 06:07:12

标签: javascript html5 canvas

按照建议编写了整个代码,但似乎没有说出来。 grid是我的2d数组,包含' words'的所有单词。数组加空方格中的随机字母。但代码不起作用。无法调试。需要帮助。谢谢。

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.");
    }

}}

1 个答案:

答案 0 :(得分:0)

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

要在单词搜索拼图中拖动选择单词,您需要以下功能:

  • 定义网格和每个网格内的字母。
  • 使用相关字母绘制网格方块。
  • 聆听mousedown事件
  • 在mousedown开始拖动操作(保存起始X / Y鼠标位置)
  • 鼠标结束时拖动操作(保存结束的X / Y鼠标位置)
  • 同样在mouseup上,检查start&amp;之间是否有字母方块。结束鼠标位置拼写拼图中剩下的一个单词
  • 如果选择了正确的拼图单词,请将其从拼图单词列表中删除

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

enter image description here

<!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>