Tips for getting rid of the ghosting effect or white background of a PNG image

As a new developer, I am currently working on my personal chess project and have recently mastered the drag and drop system. However, I would like to explore different methods for achieving this. Is there a way to eliminate the white background in the process?

  1. One potential solution could involve removing the white background from the ghost image.

  2. An alternative approach might be to replace the ghost image with the actual image being dragged.

  3. Alternatively, it could be an option to completely remove the ghost image while dragging, as the piece can still be viewed in each square when hovering over it.

If any of these solutions are feasible, it would be greatly appreciated!

Here is the link to my ongoing project: https://codepen.io/ThalisonAmaral/full/qBYZmZq. You will likely need to work with the dragstart() function.

function dragstart() {
    squaresDrop.forEach(square => square.classList.add('highlight'));
    this.classList.add('is-dragging');
}

The Drag and Drop functionality can be found towards the end of the Js Code file. Since I am not entirely sure about the specifics of what I am dealing with, I have attempted to find possible solutions by using DataTransfer.setDragImage() without much success.

I initially thought that using it could help in replacing the ghost image with an actual image, but upon further review, it doesn't seem to address the issue directly. However, I may be mistaken in my understanding.

Answer №1

To achieve this task easily, you can simply adjust the opacity of the image to 0 when dragging starts and set it back to 1 upon dropping.

I included this.style.opacity = 0; on line 105 and this.style.opacity = 1; on line 11

Hopefully, this solution meets your requirements!

/* ------- BOARD GENERATOR -------*/

const body = document.body;

const $addClass = (element,className) => {
    element.classList.add(className);
};

const $setId = (element,idName)=>{element.setAttribute('id',idName)}

const $createSquare = (element,squareColor,board)=> {
    ...
        var x = light;
        light = dark;
        dark = x;
    }
    const squares = document.querySelectorAll('.square');
    
    /*PUTTING ALL THE IDS IN EACH SQUARE */
    for (let i = 0; i < squares.length; i++) {
        $setId(squares[i],coordinates[i])
    }
    // ----- BOARD STYLE -----
    const lightSquares = document.querySelectorAll('.light');
    const darkSquares = document.querySelectorAll('.dark');

    board.style.width = size+'px';
    board.style.height = size+'px';

    lightSquares.forEach((value,index)=>{
        value.style.height = size/8+'px';
        value.style.width = size/8+'px';
        value.style.backgroundColor = lightColor;

        darkSquares[index].style.height = size/8+'px';
        darkSquares[index].style.width = size/8+'px';
        darkSquares[index].style.backgroundColor = darkColor;
    })

}

const boardzone = document.getElementById('boardzone');
createBoard(500,'white','rgb(64, 100, 145)',boardzone);

/*-------- PIECE RENDER --------*/

const king = document.createElement('img');
king.setAttribute('class','piece');
king.src = "https://images.chesscomfiles.com/chess-themes/pieces/neo/150/wk.png";
e1.appendChild(king)


/*-------- DRAG AND DROP --------*/


var audio = new Audio('sound.wav');
var pieces = document.querySelectorAll('.piece');
console.log(pieces);
var squaresDrop = document.querySelectorAll('.square');
pieceCheck = ()=> {
    ...
    function dragend(){
        this.style.opacity = 1;
        this.classList.remove('is-dragging'); 
        audio.play(); 
    }

})}
pieceCheck(); //Checking if a new piece was added in the board

squaresDrop.forEach(square=>{
    ...
})
body {
  background-color:rgb(15,15,15);
}
.board {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
}
#boardzone{
  margin: 60px auto;
  display: flex;
  justify-content:center;
}

/* Drag and Drop CSS */

.piece {
  height: 100%;
  user-select: none;
}
.highlight {
  background-color:rgba(14,14,14,0.2);
}
.is-dragging {
  cursor:move;
  opacity: 0.3;
  transform: translate(0, 0);
}
.over{
  background-color: rgba(173, 240, 118, 0.315);
} 
<div id='boardzone'></div>

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

Tips for showing error messages in response to exceptions

My function is supposed to display the response text that comes back from ex.responseText. However, every time I attempt it, it returns as "undefined" even though the text is there. onError: function (ex) { $('<div>' + ex._message + &a ...

enhancing feature to enable automatic selection of chosen option

I am facing an issue with a dropdown that utilizes ng-options in Angular. There is a default option selected with an empty value, indicated by the "selected" attribute and matching the model's value. Whenever I add a new element to the ng-options lis ...

Class Chat Practice Application

I'm a beginner in the world of programming and I could really use some assistance with troubleshooting my ChatApp. My goal is to have my server send the message "Robot: (client's username) connected" whenever someone logs on. I've been gra ...

Enhance Select Dropdown in AngularJS with Grouping and Default Selection

I am facing an issue with a form that includes a SELECT element. I have successfully loaded the possible values in my controller from a function that retrieves data from a database and groups the options by a group name. Although the list of options is lo ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

Exploring the functionality of Vue.js Multiselect with data

After making a Mounted axios call, I have received some response data from the server which is quite promising. Now, I want to extract a specific part of this data to use as an option in a multiselect :options. Here is what my Vue component looks like: ...

Could a class method be accessed from outside a nested handler method in JavaScript?

I am trying to make an XMLHttpRequest to a server using JavaScript. In the handler function, I need to call a method from the surrounding class. Is there a way to achieve this? Understanding how this works in JavaScript can be confusing. I have experiment ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Why does JavaScript return NaN when combining arrays of different lengths?

Information: Hey, take a look at these 4 arrays, and then there's an array with those arrays nested inside. I'm using _.reduce to calculate the total length of all arrays combined. However, when I run the function with the array of arrays, I&ap ...

Having trouble with the webpage not loading correctly after implementing react-router-dom

I recently installed 'react-router-dom' and 'react' in order to implement a routing feature in my project. Despite adding 'react-router-dom' to my devDependencies within the package.json file, I am encountering issues with the ...

I'm curious about how to utilize module.exports in this particular manner

I'm currently trying to wrap my head around how module.exports works with a variable in the context of a model view controller project. The explanation in the book doesn't quite click for me when it comes to this particular usage. var express = ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

Where should we place the JavaScript reference in our CSHTML file in an MVC framework?

At the beginning of our .cshtml page in our current web application, we have included the following: @using Carwale.UI.PresentationLogic; @model Carwale.Entity.ViewModels.HomeModel @{ ViewBag.CustomJS = "~/Views/StaticPartials/HomeScripts.cshtml"; ...

Validation of forms using ajax and javascript

I have implemented ajax on my webpage to dynamically change the content of a main div when different fields in the navigation bar are clicked. However, I am encountering a problem with form validation using JavaScript on elements loaded via ajax. For insta ...

"Unraveling nested data structures in React using JSON parsing

When attempting to fetch data in React from a MySQL database, I have encountered an issue where MySQL auto-escapes my values, including nested objects. While I am able to use the .json() function successfully on the top-level, I have run into problems when ...

Guide on transferring value from a <select> element using JavaScript

I'm attempting to pass the selected value of a <select> in the onChange function. I've explored this question on SO, but unfortunately, using this and this.value hasn't been successful. I understand that the question is quite old... se ...

Vuetify Chip shatters during production

Utilizing v-chip as an information banner within a Vue-Leaflet map has been the focus of my project. The chip design is based on this example here, and I have been working to adapt it accordingly. Locally, I successfully achieved my intended goal, demonstr ...

Efficiently sorting items by category name in PHP with Ajax

Currently, I am working on a functionality that involves two dropdown lists. The first one, located at the top, is for selecting a category of meals. Each option in this dropdown has an associated id_cat value. <option value="1">Pâtis ...

Error Loading JQuery: The function $() is not recognized in the Shopify platform

I seem to be overlooking something obvious. I am using Shopify and have included jQuery in the head section of the theme.liquid file: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> This script is placed rig ...

Employing the `signInWithRedirect` method with an `authDomain` that does not match the app's domain will result in an incomplete sign-in process, without any error notifications being displayed

I'm currently transitioning from using Firebase's signInWithPopup method to the signInWithRedirect method. After reading through the best practices outlined in this documentation, I realized that not following these practices can result in succe ...