简体   繁体   English

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

[英]Using kineticJS to add drag and drop functionality to images drawn on a canvas

I have a web page that I'm using to display a few images on and HTML5 canvas. 我有一个网页,用于在HTML5画布上显示一些图像。 I currently have the images displaying, and now want to make it possible to drag and drop the images around the canvas. 我目前正在显示图像,现在想使其能够在画布周围拖放图像。

After looking into how to do this, it seems to me that the best way is to use the KineticJS library available at: http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-an-image-tutorial/ 在研究了如何做到这一点之后,在我看来,最好的方法是使用KineticJS库,该库位于: http ://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-an-image -教程/

I've looked into this, but I'm not really sure how to actually use it. 我已经研究过了,但是我不确定如何实际使用它。 I've started by including the script src in my index.html file, but how do I then apply the draggable property to the images I've displayed? 我首先在index.html文件中包含脚本src,但是如何将draggable属性应用于显示的图像?

This is my index.html page: 这是我的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>

and this is the function I'm using to draw the images to the canvas: 这是我用来将图像绘制到画布上的功能:

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

            }

        }

The while loop at the bottom of this function loops through the array where I've loaded all of the images I want to draw into the JavaScript, and draws each one to a random location on the canvas. 该函数底部的while循环遍历数组,在该数组中,我已将要绘制的所有图像加载到JavaScript中,并将每个图像绘制到画布上的随机位置。

Since this is, in effect the point at which the images become JavaScript objects, I assume that this is where I need to set each one's 'draggable' property to true. 因为这实际上是图像成为JavaScript对象的地步,所以我认为这是我需要将每个人的“可拖动”属性设置为true的地方。

I've tried adding in the line 我试过加入

allImagesArray[arrayIteration].draggable = "true";

but then the browser console gives me the error, "Uncaught TypeError: Cannot set property 'draggable' of undefined". 但随后浏览器控制台给我错误,“未捕获的TypeError:无法设置未定义的可拖动属性”。

Does anyone know why this is, and how I can put it right? 有谁知道这是为什么,以及我该如何纠正?

Edit 编辑

Ok, I've got rid of that error by moving the line allImagesArray[arrayIteration].setDraggable = "true"; 好的,我通过移动allImagesArray[arrayIteration].setDraggable = "true";消除该错误allImagesArray[arrayIteration].setDraggable = "true"; to just below the context.drawImage... line in the while loop, but I'm still not able to drag and drop the images around the canvas at all. 到while循环中context.drawImage...行的下面,但是我仍然无法将图像拖放到画布上。

Does anyone know what I need to do to add the drag and drop functionality to the images? 有谁知道我需要做些什么才能向图像添加拖放功能?

For the KineticJS to make the images draggable 对于KineticJS,使图像可拖动

  1. They have to be in a KineticJS canvas, not in a custom canvas you've created. 它们必须在KineticJS画布中,而不是在您创建的自定义画布中。
  2. They have to be added as KineticJS Image object instances, not drawn directly with drawImage . 它们必须作为KineticJS Image对象实例添加,而不是直接用drawImage绘制。

See the tutorial . 请参阅教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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