簡體   English   中英

html5 canvas,當用戶單擊圖像時顯示文本

[英]html5 canvas, display text when user clicks on an image

我有一個帶有HTML5畫布的頁面,上面顯示了幾張圖像,其中有四張``描述框''圖像和許多其他圖像,每個圖像都屬於其中一個描述框。

用戶需要將每個圖像拖到其相應的描述框中。

盡管我還沒有添加將圖像拖放到框上的功能,但是目前可以在畫布上拖動圖像。

在此之前,我想為用戶添加一些“提示”。 我要這樣做的方法是,每當用戶單擊“可拖動”圖像之一或將光標懸停在描述框上方時,就會在畫布區域之外向用戶顯示文本提示。 文本提示將僅包含有關用戶選擇/懸停在哪個圖標上的更多信息。

我在畫布下面的頁面上添加了HTML5文本區域,這是我要顯示提示和提示的地方。

我有幾個JS數組,一個包含畫布上顯示的所有圖像,另一個包含所有技巧。 提示將僅在一個項目上顯示一次,因為很明顯,在任何給定時間,光標只能位於一個位置。

因此,我想使用的是'if'語句,這樣,如果用戶單擊圖像,則與該圖像相對應的文本提示將顯示在文本框中,或者如果光標懸停在描述框,則與該描述框相對應的文本提示將顯示在文本框中。

我已經使用dynamic.js庫向畫布上的圖像添加了拖放功能,盡管我使用的是我本地保存的庫的副本,因為我需要更改以下幾項:它的功能。 (我需要更改的是,最初,該庫清除了畫布上已繪制的所有內容,無論何時拖放圖像,都在拖放功能之外,而只是重新繪制了拖放功能到的圖像被添加回去,所以我在畫布上丟失了其他一些東西,這些東西我不想拖拽。)

我知道我需要進一步編輯我要使用的dynamic.js庫,以便將這些功能添加到提示中,但是我只是想知道是否有人知道如何在文本區域中從數組中顯示提示?已添加到我的頁面?

我已經看過w3schools上的“ HTML5 textarea標簽”頁面,但是看不到任何允許您定義顯示在文本區域中的文本的屬性。 我還查看了與該頁面鏈接的“事件屬性”頁面,但是看不到任何看起來像它們可以執行我想要的功能的屬性。

當用戶選擇圖像或將鼠標懸停在我的描述框之一上時,textarea是顯示我要顯示的文本的最佳方法嗎? 還是有其他東西可以顯示文本(最好在頁面的畫布區域之外),並允許我更改動態顯示的文本?

編輯以顯示HTML 31/12/2012 @ 14:40

<!DOCTYPE HTML>
<html>
  <head>
  <style>
    body {
      margin: 0px;
      padding: 0px;
    }
  canvas{
    border: 1px solid #9C9898;
    background:#F5F5F5;
  }
</style>
<div id="container"></div>
<script src="kinetic.js"></script>
<script src="drawdescriptionboxes.js"></script>
<script src="drawLevelOneElements.js"></script>
<script src="startgamedrawgameelementsdrawstartbutton.js"></script>
<script>
/*Add the game elements' global variables */
var currentLevel = 1;
var totalLevels = 3;
var currentScore = 0;
var currentScorePositionX = 950;
var currentScorePositionY = 10;

/*Add code to draw images to random locations here */
    //var imageX = Math.floor(Math.random()*950);
    //var imageY = Math.floor(Math.random()*450);

    var stage = new Kinetic.Stage({
      container: "container",
      width: 1000,
      height: 500
    });
    var imagesLayer = new Kinetic.Layer();
    var canvas = imagesLayer.getCanvas();
    var context = canvas.getContext("2d");
    console.log("Foo ");

/*Load the images from the HTML into the JavaScript */
function loadImages(sources, callback){
    var imagesDir = "";
    var images = {};
    var loadedImages = 0;
    var numImages = 0;

    //console.log("length " + sources.length);
    for (var src in sources){
        numImages++;
    }
    //console.log("Num Images " + numImages);

    var index=0;
    console.log("length " + sources.length);
    for (index=0;index < numImages ;index++){
        console.log(index);
        images[index] = new Image();
        images[index].src = sources[index];
        console.log("Adding " + sources[index]);
        callback(images[index]);
        console.log("images array length = " + images.length);
    }

    stage.add(imagesLayer); // should only be added once!!
}

/*Function to check whether the item being dragged is near its description box */
function isNearDescriptionBox(itemImage, descriptionBox){
    var ii = itemImage;
    var db = descriptionBox;
    if(ii.attrs.x > db.x - 20 && ii.attrs.x < db.x + 20 && ii.attrs.y > db.y - 20 && ii.attrs.y < db.y +20){
        return true;
    }else{
        return false;
    }
}

/* This function draws the game elements */
function drawGameElements(){
    /* Draw a line for the 'score bar'. */
    context.moveTo(0, 25);
    context.lineTo(1000, 25);
    context.stroke();

    /* Draw current level/ total levels on the left, and current score on the right. */
    context.font = "11pt Calibri"; /* Text font & size */
    context.strokeStyle = "black"; /* Font colour */
    context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
    context.strokeText(currentScore, 750, 15);
}

function initStage(images){
    var stage = new Kinetic.Stage({
        container: "container",
        width: 1000,
        height: 500
    });
    var descriptionLayer = new Kinetic.Layer();
    //var imagesLayer = new Kinetic.Layer();
    var allImages = [];
    var currentScore = 0;

    var descriptionBoxes = {
        assetsDescriptionBox: {
            x: 70,
            y: 400
        },
        liabilitiesDescriptionBox: {
            x: 300,
            y: 400
        },
        incomeDescriptionBox: {
            x: 530,
            y: 400
        },
        expenditureDescriptionBox: {
            x: 760,
            y: 400
        },
    };

    /*Code to detect whether image has been dragged to correct description box */
    for (var key in sources){
        /*Anonymous function to induce scope */
        (function(){
            var privateKey = key;
            var imageSource = sources[key];

            /*Check if image has been dragged to the correct box, and add it to that box's
                array and remove from canvas if it has */
            canvasImage.on("dragend", function(){
                var descriptionBox = descriptionBoxes[privateKey];
                if(!canvasImage.inRightPlace && isNearDescriptionBox(itemImage, descriptionBox)){
                    context.remove(canvasImage);
                    /*Will need to add a line in here to add the image to the box's array */
                }
            })

        })();
    }

}

function drawImage(imageObj) {
    //var layer = new Kinetic.Layer();

    var canvasImage = new Kinetic.Image({
      image: imageObj,
      width: 50,
      height: 50,
      // puts the image in teh middle of the canvas
      x: stage.getWidth() / 2 - 50 / 2,
      y: stage.getHeight() / 2 - 50 / 2,
      draggable: true
    });

    // add cursor styling
    canvasImage.on('mouseover', function() {
      document.body.style.cursor = 'pointer';
    });
    canvasImage.on('mouseout', function() {
      document.body.style.cursor = 'default';
    });

    imagesLayer.add(canvasImage);
}

/*This code loads the images to the canvas when the browser window loads */
window.onload = function(){
    var sources = {};
        /*I've removed the code from here which simply adds the images in the hidden section of the html to the 'sources' JS array */


    loadImages(sources, drawImage);
    drawGameElements();
    drawDescriptionBoxes();
};
/*Try adding an if statement to display the text corresponding to whichever icon is selected */
if(document.body.innerText){
    var message = div.innerText;
} else {
    var message = div.innerHTML.replace(/\&lt;br\&gt;/gi,"\n").replace(/(&lt;([^&gt;]+)&gt;)/gi, "");
}

/*What I want to do here is, detect where on the canvas the mouse has been clicked, then if the click is
    on a part of the canvas that is displaying an image, get the ID belonging to that image, and display 
    the corresponding tip from the tips array in tips.js on the page below the canvas.*/
function isClickOnImage(event){
    var clickX = event.clientX;
    var clickY = event.clientY;

    var imageCheckIteration = 0;
    while(imageCheckIteration < sources.length){
        if((clickX > sources[imageCheckIteration].x && clickX < sources[imageCheckIteration].x + imageWidth) &&
        (clickY > sources[imageCheckIteration].y && clickY < sources[imageCheckIteration].y + imageHeight)){
            /*This is where I need to print the variable that holds the text I want to display, but I need to display its contents
            outside the canvas, in the <p></p> tags below. */
            document.getElementById("tipsParagraph").innerHTML = tips[imageCheckIteration];
        }
    }
}

</script>


</head>
<body>

<p><textarea>This is where the text will be displayed.</textarea></p>

<section hidden>
/*The code in this hidden section simply loads a number of images into the html, giving them an 'id', a 'src' and an 'alt' tag. */



</section>
</body>
</html>

我刪除了用於將圖像添加到HTML的隱藏部分中以及將其從其中添加到JS數組中的代碼,只是為了減少顯示的代碼量。

編輯07/01/2013 @ 15:00

我已經編輯了代碼以顯示函數“ isClickOnImage(event)”。 當我編寫此函數時,我希望它可以更改

標記為“ tipsParagraph”的標簽與“ tips”數組中與所單擊圖像相對應的任何元素。 但是由於某些原因,當我單擊畫布上的圖像時,期望更新的段落沒有任何反應。 知道為什么嗎?

您不需要使用KineticJS的某些本機實現,在這種情況下,您僅需要將其用於事件,只需將JQuery添加到您的項目中,然后使用選擇器更改文本區域的文本即可。

  //this can easily be used in your KineticJS event function.
  $("textarea").val(message);

我建議您給您的文本區域一個id並使用$('#textAreaId')。val('hello world'); 設定您的訊息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM