html5 canvas为绘制到画布的图像添加拖放功能

时间:2012-12-03 18:09:23

标签: javascript drag-and-drop html5-canvas

我有一个带有HTML5画布的网页,我用它来在画布上显示多个图像以及四个“描述框”。

目的是用户可以将图像拖放到匹配的描述框中,但是,我在拖放工作时遇到了一些麻烦。

我已经尝试了几种不同的方法来对图像进行拖放操作,但它们似乎都无法正常工作。

我遇到的问题是要在画布上显示的内容需要是动态的,即管理员可以通过更改图像的文件名来更改画布上显示的图像等。在XML文件中使用,用于他宁愿使用的任何图像。

基本上,我想将代码添加到在画布上显示图像的JavaScript中,以便在画布上拖放它们。

有没有人对什么是最好的方法有任何建议?

我的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 = "dragAndDrop1.js" type = "text/javascript"></script>
<script src = "dragAndDrop2.js" type = "text/javascript"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.0.5.js"></script>


</head>

<body onLoad="startGame()">

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

我尝试过以三种不同的方式添加拖放功能 - 因此我已经包含了三个拖放JS文件,但这些文件似乎都不起作用。

我用来将图像绘制到画布上的JavaScript只是一些数组,每个元素都包含一个图像。我正在绘制到画布的每个图像类别都有一个数组,每个类别中的图像数量都是可变的。

然后我使用JS concat方法连接数组,将所有图像放在一个名为allImagesArray的数组中。

我有以下函数,它在画布上的随机位置从allImagesArray中绘制每个图像:

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

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

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

            }

        }

此功能还在画布上绘制了四个“描述区域”,标记为“资产”,“责任”,“收入”和“支出”。

用户需要做的是将每个图像拖动到相应的“描述区域”。当图像被拖动到​​正确的描述区域时,它应该从画布上消失。

但是虽然我在画布上绘制了图像和描述区域,但我似乎无法弄清楚如何添加拖放效果。删除图像的功能。

我在网上看过几个例子,但似乎无法让它们中的任何一个工作 - 我想知道是不是因为我是使用while循环从数组中绘制图像的?我也看过这个网站上提出的其他问题,但似乎无法找到答案。

我查看了http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-an-image-tutorial/http://www.html5canvastutorials.com/labs/html5-canvas-drag-and-drop-multiple-images-with-kineticjs/上的教程,但似乎无法使这些示例与我的代码一起使用。有没有人对如何使用我的drawLevelOneElements()函数为拖动到画布的每个图像添加拖放功能有任何想法?

1 个答案:

答案 0 :(得分:0)

在这种情况下,cgSceneGraph会很容易地帮到你。 您可以查看示例页面(演示中包含源代码): http://gwennaelbuchet.github.com/cgSceneGraph/examples.html

我是这个框架的设计者,所以我可以轻松地帮助你将它包含在你的项目中:)

使对象可拖动,就像这样:

this.img = new CGSGNodeImage(x, y, sourceURL);
this.img.isDraggable = true;
this.img.isCollisionManaged = true;

然后,要知道您的图像是否在描述区域内,您可以像这样使用cgSceneGraph的碰撞检测:

//detect collision each frame
var bindCheckCollision = this.checkCollision.bind(this);
this.onRenderEnd = function () {
    bindCheckCollision();
};

和checkCOllision方法:

checkCollision: function () {
    var isColliding = this.img.isColliding(this.descriptionNode, 0);
}

不再做:)

网站上有一个完整的例子。 希望这可以帮到你。

格温。