It seems like KineticJS is removing elements from the canvas that I would prefer to keep

My website features an HTML5 canvas where I showcase a variety of images, text, and shapes using JavaScript functions.

The text and shapes are created with the following JavaScript functions:

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

    /* Display current level/ total levels on the left, and current score on the right. */
    context.font = "11pt Calibri"; 
    context.strokeStyle = "black"; 
    context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
    context.strokeText(currentScore, 950, 15);
}

and

function drawDescriptionBoxes(){
CanvasRenderingContext2D.prototype.drawDescriptionArea = function(x, y, width, height, radius, stroke){
        if(typeof stroke == "undefined" ){
            stroke = true;
        }
        if(typeof radius === "undefined"){
            radius = 5;
        }
       //More code here
    }

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

    // More description boxes drawn here
}

The images are loaded from their sources into an HTML hidden section first, and then loaded into a JavaScript array named 'sources':

function loadImages(sources, callback){
    //Code snippet
}

Following that, I utilize another JavaScript function to draw those images onto the canvas:

function drawImage(imageObj) {
   // Code snippet
  }

While everything initially displays correctly on the canvas, when attempting to drag and drop an image, the other elements disappear. This might be due to the KineticJS library clearing the canvas entirely while redrawing the images.

I'm seeking guidance on how to retain the text and shapes drawn on the canvas while dragging and dropping the images, or ensuring they get redrawn alongside the images during this action?

Answer №1

Have you considered utilizing Kineticjs to draw the images and text initially if you are already using it?

function drawGameElements(){
    /* Utilize Kineticjs to draw a line for the 'score bar'. */
    context.moveTo(0, 25);
    context.lineTo(1000, 25);
    context.stroke();

    /* Display current level/ total levels on the left, and current score on the right. */
    context.font = "11pt Calibri"; /* Specify text font & size */
    context.strokeStyle = "black"; /* Set font color */
    context.strokeText(currentLevel + "/" + totalLevels, 10, 15);
    context.strokeText(currentScore, 950, 15);
}

You can easily convert this into a custom shape in Kineticjs, just like you have done with the contents of your drawDescriptionBoxes function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Validating form field values in JavaScript prior to submission

My website features a search box that allows users to search through a database of books. When utilizing the search feature, users are presented with the following options: Search Query (a text input field) Where to search (a select field with the option ...

Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here: https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component r ...

Is there a sweet TypeScript class constructor that can take in its own instance as an argument?

I have a scenario where I need to read in instances of Todo from a CSV file. The issue is that Papaparse does not handle dynamic conversion on dates, so I'm currently dropping the object into its own constructor to do the conversion: class Todo { ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

Encountering an unexpected token error in Vercel during deployment, even though the code runs smoothly in the

I'm facing an issue with a SyntaxError: Unexpected token '??='. I am not sure how to resolve it, so any help would be greatly appreciated. Thank you in advance. SyntaxError: Unexpected token '??=' at wrapSafe (internal/modules ...

Using React to display data from a nested JSON object in a table

I am currently working on parsing a JSON object into a table using React. However, I am facing an issue with utilizing the .map() function to create a row for every unique combination of course code, name, transferable_credits, transferable_credits -> inst ...

Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an err ...

Is it possible to use JavaScript to load, edit, and store text files?

Hey there, I have a text file that needs some find and replace operations done on it within the browser. My coding skills are still in the beginner stage, so creating web apps from scratch feels overwhelming right now. All I want to do is upload the file, ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

What causes the Vuetify checkbox to trigger twice when clicked in a Vue.js application?

I am facing an issue with a table that contains checkboxes in every row. I want to trigger some logic when a checkbox is clicked. In some cases, I need to tick multiple rows when a checkbox is clicked, so I have set the checkboxes as readonly and handle th ...

`Passing JavaScript variables through HTML anchor tags`

I am currently attempting to pass the id to the controller using this method: {{ route("admin.service.edit", '+val[0]+' )}} However, the '+val[0]+' is being interpreted as a string in the URL http://localhost:8000/admin/servi ...

How can you transfer data from a jQuery function to a designated div element?

I'm struggling to transfer data from a function to a specific div, but I can't seem to make it work. I'm in the process of creating a gallery viewer and all I want is to pass the counter variable, which I use to display images, and the total ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

Transforming the Slideshow Gallery into a fully automated gallery experience

Looking for assistance in creating an automatic rotation for this slideshow gallery. I've included the HTML, CSS, and JavaScript code for reference. As a newcomer to JavaScript, any guidance on this project would be greatly appreciated. ...

How to effectively combine css() and delay() in jQuery?

fid: https://jsfiddle.net/k13sazuz/ Is there a way to create a delay chain for CSS rules using jQuery? $('.two').css('background','blue').delay(11800).css('background','red'); ...

Deactivate the focus state when hovering over different items in the navigation bar

Currently facing an issue with my Navbar items having underline animation on hover. Once clicked, the animation persists. However, when hovering over a neighboring navbar item, the underlines appear next to each other, creating the illusion of one long lin ...

Enhancing jQuery Mobile listview with voting buttons on each item row

I am looking to incorporate 2 vote buttons within a jQuery mobile listview, positioned on the left-hand side and centered within each list item. While I have managed to achieve this using javascript, my goal is to accomplish it without any additional scrip ...

Resolving the issue: "How to fix the error "Credentials are not supported if the CORS header 'Access-Control-Allow-Origin' is '*' in React?"

Recently, I encountered some CORS issues while using a third party API in my front-end application. After reaching out to the API maintainers, they lifted the CORS control by adding a * to Access-Control-Allow-Origin, which seemed like the perfect solution ...

The jQuery change function appears to be functioning properly, but it is not producing any results

I am facing an issue with my jQuery code that rebuilds a dropdownlist based on the radio buttons selected. Although the code seems correct and the method works properly, the dropdownlist items do not update as expected. Can anyone provide some insight or i ...