Unable to show the image within the designated cropping zone

Having trouble displaying the image in the cropper. The image URL is set as the source attribute in the HTML, but the image isn't showing up. When I click the edit button, I want to show the current image (the one above the edit button) in the cropper so that I can crop the desired part of the image. After cropping the image, clicking the update button should save the changes. Any assistance with completing this task would be greatly appreciated.

window.onload = function() {
  'use strict';

  const noImage = 'https://via.placeholder.com/200x65';
  var Cropper = window.Cropper;
  var URL = window.URL || window.webkitURL;
  var container = document.querySelector('.img-container');
  var image = container.getElementsByTagName('img').item(0);
  var cropBtn = document.querySelector('#crop-btn');
  var rotate = document.querySelector('#rotate');
  var resetImage = document.querySelector('#reset');
  var zoomIn = document.querySelector('#zoomIn');
  var zoomOut = document.querySelector('#zoomOut');
  var deleteCofirmBtn = document.querySelector('#deleteCofirmBtn');
  var profilePicture = document.querySelector('#profilePicture');
  var deleteLinkContainer = document.querySelector('.deleteProfileImgWrap');
  var modal = $('#modal');
  var croppable = false;
  var options = {
    aspectRatio: 3 / 1,
    viewMode: 1,
    cropBoxResizable: false,
    guides: false,
    minContainerWidth: 300,
    minContainerHeight: 200,
    minCropBoxWidth: 200,
    minCropBoxHeight: 65,
    movable: true,
    preview: '.img-preview',
    ready: function() {
      croppable = true;
    },
  };
  var cropper = new Cropper(image, options);
  var originalImageURL = image.src;
  var uploadedImageType = 'image/jpeg';
  var uploadedImageName = '';
  var uploadedImageURL;

  var inputImage = document.getElementById('editImage');


  inputImage.addEventListener('click', function() {

    const old_image = profilePicture;
    image.src = old_image.src;
    modal.modal({
      backdrop: 'static'
    });
    cropper.destroy();
    cropper = new Cropper(image, options);


    console.log(`success`);

  });

  rotate.addEventListener('click', function() {
    cropper.rotate(90);
  });

  reset.addEventListener('click', function() {
    cropper.reset();
  });

  zoomOut.addEventListener('click', function() {
    cropper.zoom(-0.1);
  });

  zoomIn.addEventListener('click', function() {
    cropper.zoom(0.1);
  });

  deleteCofirmBtn.addEventListener('click', function() {
    profilePicture.src = noImage;
    $(".deleteProfileImgWrap").hide();
    $('.file-upload-label').parent().fadeIn();
    deleteLinkContainer.style.display = 'none';
  });

  cropBtn.addEventListener('click', function() {
    let roundedCanvas;

    let imgSrc = cropper.getCroppedCanvas({

      width: 200,
      height: 65
    }).toDataURL();
    deleteLinkContainer.style.display = 'block';

    profilePicture.src = imgSrc;

  });


}
...

Answer №1

function createRoundedCanvas(source) {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  /* var width = source.width;
  var height = source.height; */
  var width = 100;
  var height = 100;

  canvas.width = width;
  canvas.height = height;
  context.imageSmoothingEnabled = true;
  context.drawImage(source, 0, 0, width, height);
  context.globalCompositeOperation = 'destination-in';
  context.beginPath();
  context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);
  context.fill();
  return canvas;
}

window.addEventListener('DOMContentLoaded', function() {
  var image = document.getElementById('image');
  var button = document.getElementById('button');
  var output = document.getElementById('output');
  var isCroppable = false;
  var cropper = new Cropper(image, {
    aspectRatio: 1,
    viewMode: 1,
    minContainerWidth: 300,
    minContainerHeight: 200,
    minCropBoxWidth: 100,
    minCropBoxHeight: 100,
    ready: function() {
      isCroppable = true;
    },
  });

  button.onclick = function() {
    var cropped;
    var rounded;
    var roundedImg;

    if (!isCroppable) {
      return;
    }

    // Crop
    cropped = cropper.getCroppedCanvas();

    // Round
    rounded = createRoundedCanvas(cropped);

    // Show
    roundedImg = document.createElement('img');
    roundedImg.src = rounded.toDataURL()
    output.innerHTML = '';
    output.appendChild(roundedImg);
  };
});
img {
  max-width: 100%;
}

.cropper-view-box,
.cropper-face {
  border-radius: 50%;
}

.cropper-point.point-se {
  height: 5px !important;
  width: 5px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<link href="https://fengyuanchen.github.io/cropperjs/css/cropper.css" rel="stylesheet" />
<script src="https://fengyuanchen.github.io/cropperjs/js/cropper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet" />
<div class="container-fluid">
  <div class="row">
    <div class="col-sm-12">
      <div id="output"></div>
      <a href="#" data-toggle="modal" data-target="#myPopup">Edit</a>
    </div>
  </div>
</div>
<div class="modal" id="myPopup">
  <div class="modal-dialog">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Modify Popup</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>

      <!-- Modal body -->
      <div class="modal-body">
        <div>
          <img id="image" src="https://fengyuanchen.github.io/cropperjs/images/picture.jpg" alt="Picture">
          <!-- <img id="image" src="https://d1shuhu6tm6s0s.cloudfront.net/piimages/find-suppliers/Paper_Manufactures_PaperIndex_Map.png" alt="Picture">
                  </div> -->
        </div>
        <div class="modal-footer">
          <button id="button" type="button" class="btn btn-success" data-dismiss="modal">Update</button>
        </div>
      </div>
    </div>
  </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

What is the best method for retrieving data using Selenium when the class name may vary slightly?

Hypothetically, let's consider the following HTML code snippet displayed on a website: <div class="box"> <div class="a1"></div> <div class="a2"></div> <div class="a3" ...

The functionality of Angular binding seems to be experiencing some issues

Just starting out with angular and trying to figure things out. I've made an HTML page where the user can input text into a textbox, and whatever is entered should simultaneously appear on the screen. Here is the HTML code snippet: <html ng-app&g ...

Python raises a KeyError if JQuery is included

I have encountered an issue with the code snippet below, where I am attempting to define a variable within the HTML. Oddly enough, when I exclude the JQuery script, everything functions as expected. However, upon reintroducing the JQuery script, the functi ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...

Show a virtual numeric keypad on the HTML input fields when they are set as type text specifically for mobile devices in a unique situation

When accessing the following web page from a mobile device, I currently have number input fields with comma separators added. However, in order to implement the comma separation function, I had to set the input type to text. This resulted in showing an alp ...

A Step-by-Step Guide to Downloading Images by Clicking

Having an issue with my image download code. When I try to download an image, the process starts but doesn't complete and no file is received. Instead, a type error is encountered. <html> <head> <script type="text/javascript"> funct ...

Discover the secret to easily displaying or concealing the form of your choice with the perfect fields

Greetings! I require assistance in understanding how to hide or display a form. Specifically, I have two forms - studentForm and EmployeeForm. When selected from the dropdown list profileType, I want the corresponding form to be displayed. I am facing an ...

Automatically updating markers on Google Maps v3

I'm utilizing the capabilities of Google Maps V3 to showcase various pins. My goal is to update these markers periodically without interfering with the current location or zoom level on the map. I aim for the markers to refresh every x seconds. How c ...

Sending a large base64-encoded file via Ajax POST using a mobile device

I have a Canvas where clients can sign a form on my website. The base64 string is sent through an AJAX POST to a Node.js server, and it works fine regardless of the file size when I run the process on my computer. If the signature is small, it can also be ...

Ajax fails to transmit information

Currently, I am in the process of familiarizing myself with the usage of ajax. An issue that I am encountering is that clicking a submit button in a form does not effectively send data. Below you can find the JQuery code I am using: $('input[name=" ...

How can you transfer a function to another function within the render return statement?

I am encountering an issue when attempting to pass a function to another function. The initial function successfully downloads JSON data and returns it. However, the subsequent function, which is meant to convert the JSON data to HTML code, is not functio ...

Turn off the ability to view the content of .css and .js files within the browser

Earlier, I inquired about how to disable file and folder listing and discovered that it can be achieved using a file named .htaccess. To disable folder listing, I entered Options -Indexes in the .htaccess file located in the parent folder. Additionally, to ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Recording videos using the Safari Browser

Within my ReactJs application, I have integrated react-multimedia-capture, a package that utilizes navigator.mediaDevices.getUserMedia and the MediaRecorder API to facilitate video recording. While I am successfully able to record videos on Chrome, Safari ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Verify the functionality of a specific method invoked within another method through unit testing

I currently have a method in my Angular application that is triggered upon clicking. Inside this method, I pass a value to another private method. .ts file public onViewItem(item: Results): void { const ids = [item.data['id']]; this.anot ...

Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB My goal is to modify the JavaScript so that the scroll height is based on a p ...

Adjust the location.hash and then navigate using the Back button - Internet Explorer displays unique behavior compared to other web browsers

When updating `location.hash`, all browsers behave correctly by only changing the URL without refreshing the page. However, pressing the Back button in Internet Explorer and other browsers results in different behaviors. IE fails to update the history wit ...

Retrieving an image from a JSON file based on its corresponding URL

I am trying to extract the URL and display it as an image: This is how it appears in JSON: https://i.sstatic.net/vpxPK.png This is my HTML code: <ul> <li *ngFor="let product of store.Products"> <p>Product Image: {{ product.Pr ...

What is the best way to extract specific information from a deeply nested document in MongoDB?

In my database, I have the following data structure. [ { _id: ObjectId("6386ef039775398be3620c76"), firstName: 'A', lastName: 'BA', age: 34, history: [ { disease: 'fever', cured: true }, ...