使用kineticJS为画布上绘制的图像添加拖放功能

时间:2012-12-06 20:14:43

标签: javascript html5-canvas draggable kineticjs

我有一个网页,我用它来显示一些图像和HTML5画布。我目前正在显示图像,现在希望能够在画布上拖放图像。

在研究如何做到这一点之后,在我看来,最好的方法是使用可用的KineticJS库:http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-an-image-tutorial/

我已经调查了这个,但我不确定如何实际使用它。 我已经开始在我的index.html文件中包含脚本src,但是如何将draggable属性应用于我显示的图像?

这是我的index.html页面:

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


</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"/>

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

这是我用来将图像绘制到画布上的函数:

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 */
                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);

            }

        }

此函数底部的while循环遍历数组,我已将所有要绘制的图像加载到JavaScript中,并将每个图像绘制到画布上的随机位置。

因为这实际上是图像成为JavaScript对象的点,我认为这是我需要将每个'draggable'属性设置为true的地方。

我已尝试添加

allImagesArray[arrayIteration].draggable = "true";

然后浏览器控制台给出了错误,“Uncaught TypeError:无法设置属性'draggable'of undefined”。

有谁知道为什么会这样,我怎么能说得对?

修改

好的,我已经通过将行allImagesArray[arrayIteration].setDraggable = "true";移动到while循环中context.drawImage...行的正下方来消除该错误,但我仍然无法拖放图像在画布周围。

有没有人知道我需要做些什么来为图像添加拖放功能?

1 个答案:

答案 0 :(得分:0)

让KineticJS使图像可拖动

  1. 他们必须在KineticJS画布中,而不是在您创建的自定义画布中。
  2. 必须将其添加为KineticJS Image object个实例,而不是直接使用drawImage绘制。
  3. 请参阅tutorial