html5画布拖放图像

时间:2012-12-08 15:47:27

标签: javascript javascript-events html5-canvas

我有一个带有HTML5画布的网页,它使用JavaScript在画布上显示许多图像。我在画布上还有四个“描述区域”,它们是使用以下JavaScript函数绘制的:

CanvasRenderingContext2D.prototype.drawDescriptionArea = function(x, y, width, height, radius, stroke){
        if(typeof stroke == "undefined" ){
            stroke = true;
        }
        if(typeof radius === "undefined"){
            radius = 5;
        }
        this.beginPath();
        this.moveTo(x + radius, y);
        this.lineTo(x + width - radius, y);
        this.quadraticCurveTo(x + width, y, x + width, y + radius);
        this.lineTo(x + width, y + height - radius);
        this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        this.lineTo(x + radius, y + height);
        this.quadraticCurveTo(x, y + height, x, y + height - radius);
        this.lineTo(x, y + radius);
        this.quadraticCurveTo(x, y, x + radius, y);
        this.closePath();
        if(stroke){
            context.stroke();
        }
    }

我想为我在画布上显示的图像添加拖放功能,以便用户可以将每个拖放到相应的描述区域。当每个图像被拖动到​​其相应的描述区域时,它应该从画布上消失。如果图像被拖动到​​错误的描述区域,图像应保留在画布上,并且应显示一条消息,指出用户选择不正确。

我目前正致力于为图像添加拖放功能,但是我在使用它时遇到了一些麻烦。

我找到了一个关于我在网上尝试做什么的例子,并且我试图遵循这个,但显然要让它在我使用它的上下文中工作。我关注的示例位于:http://html5demos.com/drag

我查看了此示例中的源代码,并尝试重用代码,将拖放功能添加到画布上的图像中。这是我到目前为止所得到的:

<!DOCTYPE html>
<html>
<head>
<script src = "kinetic.js" type = "text/javascript"></script>
<title>Home</title>

<script src = "drawLevelOneElements.js" type = "text/javascript"></script>
<script src = "layers&analytics.js" type = "text/javascript"></script>
<script src = "startGameDrawGameElementsDrawStartButton.js" type = "text/javascript"></script>
<script src = "interaction.js" type = "text/javascript"></script>
<script src = "dragAndDrop.js" type = "text/javascript"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.5.js"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.1.2.js"></script>
<script src="draggable.js"></script>


</head>

<body onLoad="startGame()">

<section hidden>
<img id="StartButton" src="StartButton.png" alt="Start Button" width="179" height="180" href="javascript:drawLevelOneElements();"/>

<img id="building" src="images/assets/building.png" alt="Asset" draggable="true" ondragstart="drag(event)"/>
<img id="chair" src="images/assets/chair.gif" alt="Asset"/>
<img id="drink" src = "images/assets/drink.jpg" alt="Asset"/>
<img id="food" src = "images/assets/food.gif" alt="Asset"/>
<img id="fridge" src = "images/assets/fridge.png" alt="Asset"/>
<img id="land" src = "images/assets/land.jpg" alt="Asset"/>
<img id="money" src = "images/assets/money.jpg" alt="Asset"/>
<img id="oven" src = "images/assets/oven.jpg" alt="Asset"/>
<img id="table" src = "images/assets/table.gif" alt="Asset"/>
<img id="van" src = "images/assets/van.jpg" alt="Asset"/>

<img id="burger" src = "images/expenses/direct/burger.png" alt="Direct Expense"/>
<img id="chips" src = "images/expenses/direct/chips.png" alt="Direct Expense"/>
<img id="drink" src = "images/expenses/direct/drink.jpg" alt="Direct Expense"/>
<img id="franchiseFee" src = "images/expenses/direct/franchiseFee.jpg" alt="Direct Expense"/>
<img id="wages" src = "images/expenses/direct/wages.jpg" alt="Direct Expense"/>

<img id="admin" src = "images/expenses/indirect/admin.jpg" alt="Indirect Expense"/>
<img id="cleaners" src = "images/expenses/indirect/cleaners.gif" alt="Indirect Expense"/>
<img id="electricity" src = "images/expenses/indirect/electricity.gif" alt="Indirect Expense"/>
<img id="insurance" src = "images/expenses/indirect/insurance.jpg" alt="Indirect Expense"/>
<img id="manager" src = "images/expenses/indirect/manager.jpg" alt="Indirect Expense"/>
<img id="rates" src = "images/expenses/indirect/rates.jpg" alt="Indirect Expense"/>
<img id="training" src = "images/expenses/indirect/training.gif" alt="Indirect Expense"/>
<img id="water" src = "images/expenses/indirect/water.gif" alt="Indirect Expense"/>

<img id="burger" src = "images/income/burger.png" alt="Income"/>
<img id="chips" src = "images/income/chips.png" alt="Income"/>
<img id="drink" src = "images/income/drink.jpg" alt="Income"/>

<img id="creditors" src = "images/liabilities/creditors.gif" alt="Liability"/>
<img id="electricity" src = "images/liabilities/electricity.png" alt="Liability"/>
<img id="food" src = "images/liabilities/food.jpg" alt="Liability"/>
<img id="hirePurchase" src = "images/liabilities/hirePurchase.jpg" alt="Liability"/>
<img id="loan" src = "images/liabilities/loan.png" alt="Liability"/>
<img id="overdraft" src = "images/liabilities/overdraft.jpg" alt="Liability"/>
<img id="payeTax" src = "images/liabilities/payeTax.jpg" alt="Liability"/>
<img id="tax" src = "images/liabilities/tax.jpg" alt="Liability"/>

This code has been added based on example at: http://html5demos.com/drag#view-source
Code as far as the end of the section.

<div id="bin"></div>
<ul>
<li><a id="building" href="#"</a></li>
<li><a href="#" id="chair"></li>
<li><a href="#" id="drink"></li>
<li><a href="#" id="food"></li>
<li><a href="#" id="fridge"></li>
<li><a href="#" id="land"></li>
<li><a href="#" id="money"></li>
<li><a href="#" id="oven"></li>
<li><a href="#" id="table"></li>
<li><a href="#" id="van"></li>
</ul>

<script>
var drop = ['Correct!', 'Incorrect!'];
var feedback = document.createElement('p');
var msie = /*@cc_on!@*/0;
feedback.style.opacity = 1;

var imagesToMakeDraggable = document.querySelectorAll('li > a'), el = null;
for (var i = 0; i < imagesToMakeDraggable.length; i++){
    el = imagesToMakeDraggable[i];
    el.setAttribute('draggable', 'true');

    addEvent(el, 'dragstart', function(e){
        e.dataTransfer.effectAllowed = 'copy'; /*Only dropEffect='copy' will be dropable */
        e.dataTransfer.setData('Image', this.id); /*Required otherwise, doesn't work */
    });
}

var bin = document.querySelector('#bin');

addEvent(bin, 'dragover', function(e){
    if(e.preventDefault) e.preventDefault(); /*Allows us to drop */
    this.className = 'over';
    e.dataTransfer.dropEffect = 'copy';
    return false;
});

/*To get IE to work */
addEvent(bin, 'dragenter', function(e){
    this.className = 'over';
    return false;
});

addEvent(bin, 'dragleave', function(){
    this.className = '';
});

addEvent(bin, 'drop', function(e){
    if(e.stopPropagation) e.stopPropagation(); /*Stops the browser from redirecting... why? */
    var el = document.getElementById(e.dataTransfer.getData('Image'));
    el.parentNode.removeChild(el);

    /*Stupid nom text & fade effect */
    bin.className = '';
    feedback.innerHTML = drop[parseInt(Math.random() * drop.length)];

    var f = feedback.cloneNode(true);
    bin.appendChild(f);

    setTimeout(function(){
        var t = setInterval(function(){
            if(f.style.opacity <= 0){
                if(msie) { /*Don't bother with the animation */
                    f.style.display = 'none';
                }
                clearInterval(t);
            } else {
                f.style.opacity -= 0.1;
            }
        }, 50);
    }, 250);
    return false;
});

</script>


</section>

    <h1>Home</h1>
    <p>The purpose of this website is to teach users the basic principles of running a business by playing the game below. <br /><br /></p>

    <canvas id="gameCanvas" width="1000" height="500" style="border:1px solid">
    Your browser does not support the canvas element.
    </canvas>

    <br /><br />
    <p>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.</p>

    <script src = "variables&preloadingImages.js" type = "text/javascript"></script>
</body>

我有大量的图像正在绘制到画布上,所以我只是尝试将拖放功能添加到第一组图像中。

但是,当我现在在浏览器中查看我的页面时,已添加了行

下面的代码
  

此代码已根据以下示例添加:http://html5demos.com/drag#view-source   代码一直到该部分的结尾。

基于我之前提到的网页上的示例,出于某种原因,浏览器似乎认为整个页面现在是一个超链接(即当鼠标悬停时,光标是'手'而不是'指针'几乎在整个页面的任何地方,所有文本和画布边框都变成紫色和下划线,好像它都是一个超链接。

如果我点击光标变为“手”的页面上的任何位置,则所有文本和画布边框都会从紫色变为红色,例如单击超链接时。

单击画布上显示的“开始按钮”会调用“drawLevelOneElements()”函数,该函数将所有图像和描述区域绘制到画布上,但仍然无法拖放和删除画布周围的图像。

任何人都可以看到我在这里做错了什么,以及我需要做些什么才能让图片在画布上拖放?

我的'drawLevelOneImages()'函数的代码是:

/* This function draws the elements for level 1. */
function drawLevelOneElements(){
    /*First, clear the canvas */ 
    context.clearRect(0, 0, myGameCanvas.width, myGameCanvas.height);
    /*This line clears all of the elements that were previously drawn on the canvas. */
    /*Then redraw the game elements */
    drawGameElements(); 
    /*Call the function to enable drag and drop */
    canvasState(document.getElementById('gameCanvas'));

    /*Create the four description areas, and place them near the bottom of the canvas */
    /*Create boxes with rounded corners for the description areas */
    CanvasRenderingContext2D.prototype.drawDescriptionArea = function(x, y, width, height, radius, stroke){
        if(typeof stroke == "undefined" ){
            stroke = true;
        }
        if(typeof radius === "undefined"){
            radius = 5;
        }
        this.beginPath();
        this.moveTo(x + radius, y);
        this.lineTo(x + width - radius, y);
        this.quadraticCurveTo(x + width, y, x + width, y + radius);
        this.lineTo(x + width, y + height - radius);
        this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        this.lineTo(x + radius, y + height);
        this.quadraticCurveTo(x, y + height, x, y + height - radius);
        this.lineTo(x, y + radius);
        this.quadraticCurveTo(x, y, x + radius, y);
        this.closePath();
        if(stroke){
            context.stroke();
        }
    }

    context.drawDescriptionArea(70, 400, 120, 70);
    context.font = '25pt Calibri';
    context.strokeText('Asset', 90, 440);

    context.drawDescriptionArea(300, 400, 120, 70);
    context.strokeText('Liability', 310, 440);

    context.drawDescriptionArea(540, 400, 120, 70);
    context.strokeText('Income', 550, 440);

    context.drawDescriptionArea(750, 400, 180, 70);
    context.strokeText('Expenditure', 760, 440);

    /*Now draw the images to the canvas */
    /*First, create variables for the x & y coordinates of the image that will be drawn.
    the x & y coordinates should hold random numbers, so that the images will be 
    drawn in random locations on the canvas.*/
    var imageX = Math.floor(Math.random()*100);
    var imageY = Math.floor(Math.random()*100);
    var imageWidth = 50;
    var imageHeight = 50;

    /*Create a 'table' of positions that the images will be drawn to */
    var imagePositionsX = [20, 80, 140, 200, 260, 320, 380, 440, 500, 560];
    var imagePositionsY = [20, 60, 100, 140, 180, 220, 260, 300, 340, 380];

    /*Draw all images from assetsImageArray */
    /*Use a while loop to loop through the array, get each item and draw it. */
    var arrayIteration = 0;
    console.log('All Images Array length: ' + allImagesArray.length); /*Display the length of the array in the console, to check it's holding the correct number of images. */
    while(arrayIteration < allImagesArray.length){
        //var randomPositionX = Math.floor(Math.random()*10);
        //var randomPositionY = Math.floor(Math.random()*10);
        context.drawImage(allImagesArray[arrayIteration], imageX, imageY, imageWidth, imageHeight); /*Declare variables for image height and width, so it can be accessed elsewhere */
        //allImagesArray[arrayIteration].setDraggable = "true";
        allImagesArray[arrayIteration].setAttribute('draggable', 'true');
        console.log(arrayIteration); /*Display the current array position that's being drawn */
        arrayIteration = arrayIteration+1;
        /*Now try changing the values of imageX & imageY so that the next image is drawn to a 
        different location*/
        //imageX = imagePositionsX[randomPositionX];    /* imageX+(Math.floor(Math.random()*100)); */
        //imageY = imagePositionsY[randomPositionY];    /* imageY+(Math.floor(Math.random()*100));  */
        imageX = Math.floor(Math.random()*950);
        imageY = Math.floor(Math.random()*350);

    }

}

0 个答案:

没有答案