Select only the transparent area to upload your image

Below Mask image has 3 parts:

  1. Outside Non-Transparent Part
  2. Border
  3. Inside Transparent part

https://i.sstatic.net/Uxc5n.png

Currently, when a user clicks on the Transparent or Non-Transparent part, they are allowed to upload an image.

Requirement:

When a user clicks on the Non-Transparent part, the dialogue box should not display for uploading an image.

Link: https://codepen.io/kidsdial/pen/jJBVON

var mask;

let jsonData = {
    "path": " love shape\/",
    "info": {
        "author": "",
        "keywords": "",
        "file": "love shape",
        "date": "sRGB",
        "title": "",
        "description": "Normal",
        "generator": "Export Kit v1.2.8"
    },
    "name": "love shape",
    "layers": [{
        "x": 1,
        "height": 613,
        "layers": [{
                "x": 1,
                "color": "0xFFFFFF",
                "height": 612,
                "y": 30,
                "width": 612,
                "shapeType": "rectangle",
                "type": "shape",
                "name": "bg_rectangle_1"
            },
            {
                "x": 40,
                "height": 480,
                "layers": [{
                        "x": 10,
                        "height": 480,
                        "src": "ncdHNan.png",
                        "y": 10,
                        "width": 514,
                        "type": "image",
                        "name": "mask_image_1"
                    },
                    {
                        "radius": "27 \/ 27",
                        "color": "0xACACAC",
                        "x": 233,
                        "y": 205,
                        "height": 53,
                        "width": 53,
                        "shapeType": "ellipse",
                        "type": "shape",
                        "name": "useradd_ellipse1"
                    }
                ],
                "y": 1,
                "width": 514,
                "type": "group",
                "name": "user_image_1"
            }
        ],
        "y": 1,
        "width": 614,
        "type": "group",
        "name": "loveshape_18"
    }]
};

$(document).ready(function() {

    $('.container').click(function(e) {
        setTimeout(() => {
            $('#fileup').click();
        }, 20)
    });

    function getAllSrc(layers) {
        let arr = [];
        layers.forEach(layer => {
            if (layer.src) {
                arr.push({
                    src: layer.src,
                    x: layer.x,
                    y: layer.y
                });
            } else if (layer.layers) {
                let newArr = getAllSrc(layer.layers);
                if (newArr.length > 0) {
                    newArr.forEach(({ src, x, y }) => {
                        arr.push({
                            src,
                            x: (layer.x + x),
                            y: (layer.y + y)
                        });
                    });
                }
            }
        });
        return arr;
    }

    function json(data)

    {
        var width = 0;
        var height = 0;
        let arr = getAllSrc(data.layers);

        let layer1 = data.layers;
        width = layer1[0].width;
        height = layer1[0].height;

        for (let { src, x, y } of arr) {
            $(".container").css('width', width + "px").css('height', height + "px").addClass('temp');

            var mask = $(".container").mask({
                maskImageUrl: 'https://i.imgur.com/' + src,
                onMaskImageCreate: function(img) {

                    img.css({
                        "position": "absolute",
                        "left": x + "px",
                        "top": y + "px"
                    });
                }
            });

            fileup.onchange = function() {
                mask.loadImage(URL.createObjectURL(fileup.files[0]));
            };
        }

    }
    json(jsonData);
});

Answer №1

In the query presented, it is mentioned that the heart should be transparent while the rest of the canvas remains opaque. However, upon reviewing your code, it seems that the heart is actually being drawn as opaque with the background remaining transparent. For the purpose of this explanation, I will proceed under the assumption of the latter scenario.

Given that you are utilizing a canvas element for the drawing process, we can leverage its functionality in the following manner:

$('.container').click(function(e) {
  if(e.target.getContext) {
    var pixel = e.target.getContext('2d').getImageData(e.offsetX, e.offsetY, 1, 1).data;
    if(pixel[3] === 255) {
      setTimeout(() => {
          $('#fileup').click();
      }, 20);
    }
  }
});

The e.target signifies the specific element that was clicked on. By verifying whether it possesses the getContext property, we can ascertain if it corresponds to a canvas. If not, no file dialog will be triggered.

If the clicked element is indeed a canvas, we can progress to the subsequent stage. Calling getContext('2d') enables us to access the canvas' drawing context, allowing retrieval of raw pixel data via getImageData().

The offsetX and offsetY attributes from the event denote the coordinates of the click relative to the clicked element. These values are utilized in getImageData() to extract information about the pixel at the specified location on the canvas.

The pixel data comprises interleaved red, green, blue, and alpha (opacity) values, each ranging between 0 and 255. As only a single pixel is retrieved, there will be four values, with the last representing the alpha channel. This information assists in determining whether the file dialog should be activated based on the opacity of the pixel.

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

Using PHP, JavaScript, and Bootstrap to display success or error messages for form fields through AJAX

I am working on a form where users input an 'authorisation code' that is then checked against a database using AJAX and PHP. Currently, the form displays a tick if the code is valid and a cross if it is incorrect. I would like to utilize Bootstra ...

What is the best way to implement a dropdown menu with JavaScript or jQuery?

I'm looking to create a dynamic dropdown list using Javascript or JQuery that mirrors the functionality of selecting countries, states, and cities. Can someone provide guidance on the best code to achieve this? Below is a snippet of my existing code: ...

Issue with sticky navbar becoming glitchy and shaky when resized while scrolling in Bootstrap

Attempting to make the navbar shrink and change color gradually upon scrolling, I added a transition CSS property to achieve this effect. However, during testing, I encountered a serious glitch where the navbar starts shaking violently up and down at a ce ...

The navigation bar is failing to redirect to another page upon clicking in Bootstrap 5

The problem arises when attempting to navigate with the navbar item, as it fails to redirect to the intended page and provides no feedback. However, upon removing the bootstrap.bundle.min.js, the redirect feature operates as expected. Nonetheless, the coll ...

What is the process for interacting with DOM Elements in Node JS?

JAVASCRIPT FILE const path = require('path'); const http = require('http'); const fs = require('fs'); const dir = '../frontend/'; const server = http.createServer((request, respond) => { console.log(reques ...

Could using an image defer script instead of a lazy image script result in an undefined offset error?

To enhance the pagespeed of my website, Pagespeed Insight recommends using deferred images instead of lazy jQuery images. In an effort to follow this advice, I made adjustments based on suggestions from another source. Read more on stackoverflow I utiliz ...

I am receiving a Promise object with a status of "pending" within an asynchronous function on node.js

I have a nodejs class function that retrieves all rows from the database. module.exports = class fooClass { static async fooFunc() { const mysql = require('mysql'); const util = require('util'); const conn = mysql.createC ...

A recursive function that utilizes a for loop is implemented

I am encountering a critical issue with a recursive function. Here is the code snippet of my recursive function: iterateJson(data, jsonData, returnedSelf) { var obj = { "name": data.groupName, "size": 4350, "type": data.groupType }; if ...

The element refuses to accept the appendChild method

I've created a tampermonkey script that generates certain elements and adds them to the page. The first element, named ControllerBG, is appended to an element with the id "motd". However, when I try to append a second element, nothing appears on the ...

React Native: Implementing scroll-based header animations in ScrollView

Currently, I am working on implementing an animated header with ScrollView on the screen. In this implementation, I need to set my view based on the Y position of the ScrollView during scrolling. This is how it's done: const onScroll = ({ nativeEvent: ...

Efficient ways to organize JSON objects using JavaScript

I am in need of restructuring the data retrieved from an API call, which currently looks like this: { "Label3": [ { "name": "superman", "power": 8900 }, { "name": "iron man", "power": 3000 }, { "name": "spike spiegal", "power": 200 ...

What is the optimal location for making API requests in a React/Redux/Reach Router application?

I'm struggling to figure out the optimal location for making API calls in my app. My main component structure looks like this: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> ...

Intermittent issues with the jQuery function are causing inconsistencies in

Feeling a bit stuck at the moment. I'm currently using an AJAX live search lookup script to find customers in my database through an input field. Once I select a customer, their details are supposed to populate the form I'm working on. However, ...

Adjusting the NVM Node version with a Bash script

I'm currently working on creating aliases in my .bash_profile file with specific functionalities: xx projname => cd ~/folder_1/projname and ensure nvm uses node version 6 if it's not already using that version yy projname => cd ~/f ...

Edit the information within an element

Seeking assistance in swapping out text within anchor tags (<a>here</a>) on a website built with Wordpress. Unable to alter the HTML directly, so looking to use Jquery or PHP. The challenge lies in the lack of classes or IDs for the anchor tag ...

What is the best way to handle .jsx files in my library bundling process with Rollup?

Currently, I am in the process of developing a component library using storybook and rollup. Here is the configuration file rollup.config.mjs /* eslint-disable import/no-extraneous-dependencies */ import peerDepsExternal from 'rollup-plugin-peer-deps- ...

What are the steps to integrate my server-side PHP code into this form wizard?

Having created a straightforward 3 step form wizard for registration, I encountered an issue at the last stage when users click on submit. The desired action is to direct users to the PHP code that has been written. Update: Despite updating the HTML code ...

What is the best way to input keys into the currently selected element?

During my experimentation, I discovered that several modals and dropdowns in my tests open with their input boxes automatically focused. I found a way to verify if an element is in focus, but I'm wondering if there's a quicker method to input ke ...

Establishing an infoWindow for a series of markers generated within a callback function for the directionsService

I am facing a challenge with setting infoWindows for markers that are created within the callback function of a directionsService using Google Maps API V3. Despite trying various approaches, I have not been successful in achieving this task... Below is an ...

Is it possible to trigger a single event listener by either of two events?

I need a search functionality that triggers a method on a bean either through a click event or a blur event, whichever occurs first. This is necessary because I want the search results to display as the user types, but also to work if the user copies and p ...