Crop image in triangle shape using cropper.js

If you want to crop image into triangle shape by using cropper.js then this blog for you. We will create live demo for you so will get idea how programmatically crop your image in triangle shape. We are using Cropper.js JavaScript library to crop an image in triangle shape.

crop image in triangle shape

What is cropper.js?

Cropper.js is a JavaScript library for cropping image. With the Cropper.js, you can select an specific area of an image, and then upload the coordinates data to server-side to crop the image, or crop the image on browser-side directly.

Step 1: Create one simple web page and add below code in one html file.

<html>
  <head>
    <title>How to crop image in triangle shape by using Cropper.js</title>
    <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css" />
  </head>
  <style>
    .container {
      margin: 20px auto;
      max-width: 640px;
    }

    img {
      max-width: 100%;
    }

    .cropper-view-box,
    .cropper-face {
      /*border-radius: 50%;*/
      clip-path: polygon(1% 78%, 46% 2%, 49% 0, 54% 0, 57% 2%, 98% 78%, 98% 83%, 95% 87%, 89% 88%, 6% 89%, 2% 87%, 0 83%);
    }

    /* The css styles for `outline` do not follow `border-radius` on iOS/Safari (#979). */
    .cropper-view-box {
      outline: 0;
      box-shadow: 0 0 0 1px #39f;
    }
  </style>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-lg-6" align="center">
          <label onclick="start_cropping()">Browse image</label>
          <div id="display_image_div">
            <img name="display_image_data" id="display_image_data" src="dummy-image.png" alt="Picture">
          </div>
          <br>
          <input type="file" name="browse_image" id="browse_image" class="form-control">
        </div>
        <div class="col-lg-6" align="center">
          <label>Preview</label>
          <div id="cropped_image_result">
            <img style="width: 350px;" src="dummy-image.png" />
          </div>
          <br>
          <button type="button" class="btn btn-success" id="crop_button">Crop</button>
          <button type="button" class="btn btn-danger" id="download_button" onclick="download()">Download</button>
          <button type="button" class="btn btn-warning" id="upload_button" onclick="upload()">Upload</button>
        </div>
      </div>
      <!--  end row -->
    </div>
    <!-- end container -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
  
  </body>
</html>

In this code we have added bootstrap.min.css and cropper.min.css which is used for design a web page and cropping image. We also added some JavaScript library jquery-3.5.1.min.js, bootstrap.min.js and cropper.min.js which is most useful for cropping an image in triangle shape.

Step 2: Write some JavaScript code for crop an image in triangle shape.

    <script>
      $("body").on("change", "#browse_image", function(e) {
            var files = e.target.files;
            var done = function(url) {
              $('#display_image_div').html('');
              $("#display_image_div").html(' < img name = "display_image_data"
                id = "display_image_data"
                src = "'+url+'"
                alt = "Uploaded Picture" > ');
              };
              if (files && files.length > 0) {
                file = files[0];
                if (URL) {
                  done(URL.createObjectURL(file));
                } else if (FileReader) {
                  reader = new FileReader();
                  reader.onload = function(e) {
                    done(reader.result);
                  };
                  reader.readAsDataURL(file);
                }
              }
              var image = document.getElementById('display_image_data');
              var button = document.getElementById('crop_button');
              var result = document.getElementById('cropped_image_result');
              var croppable = false;
              var cropper = new Cropper(image, {
                aspectRatio: 1,
                viewMode: 1,
                ready: function() {
                  croppable = true;
                },
              });
              button.onclick = function() {
                var croppedCanvas;
                var roundedCanvas;
                var roundedImage;
                if (!croppable) {
                  return;
                }
                // Crop
                croppedCanvas = cropper.getCroppedCanvas();
                // Round
                roundedCanvas = getRoundedCanvas(croppedCanvas);
                // Show
                roundedImage = document.createElement('img');
                roundedImage.src = roundedCanvas.toDataURL()
                result.innerHTML = '';
                result.appendChild(roundedImage);
              };
            });

          function getRoundedCanvas(sourceCanvas) {
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            var width = sourceCanvas.width;
            var height = sourceCanvas.height;
            canvas.width = width;
            canvas.height = height;
            context.imageSmoothingEnabled = true;
            context.drawImage(sourceCanvas, 0, 0, width, height);
            context.globalCompositeOperation = 'destination-in';
            context.beginPath();
            /*context.moveTo(0, width)
            context.lineTo(width, 0)
            context.lineTo(height, width)*/
            context.moveTo(0, width)
            context.lineTo(width / 2, 0)
            context.lineTo(height, width)
            context.fill();
            return canvas;
          }
    </script>

Step 3: To download cropped image you need to use below function code.

function download() {
    var linkSource = $('#cropped_image_result img').attr('src');
    var fileName = 'download.png';
    const downloadLink = document.createElement("a");
    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
}

Step 4: For upload an image on server then you need to use below function.

function upload() {
    var base64data = $('#cropped_image_result img').attr('src');
    //alert(base64data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "crop_image_upload.php",
        data: {
            image: base64data
        },
        success: function(response) {
            if (response.status == true) {
                alert(response.msg);
            } else {
                alert("Image not uploaded.");
            }
        }
    });
}

Step 5: Now once you create above function you need to create one PHP file and add below code.

<?php
$folderPath = 'upload_images/';
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.png';
file_put_contents($file, $image_base64);
$response = array(
                'status' => true,
                'msg' => 'Image uploaded on server successfully!',
				'file' => $file
            );
echo json_encode($response);
?>

Step 6: Finally you need to create one folder where will store or save cropped image in that folder.

Image upload path

In above example we will cove all the below points:

  1. How do I crop a triangle image?
  2. How do you crop an image in JavaScript?
  3. How do you crop a picture in a triangular shape?
  4. How do I crop picture into shape?
  5. How to crop image in triangle shape using JavaScript?

Related Posts

Divyesh Patel

I'm Divyesh Patel, Web & App developer. I want to make things that make a difference. With every line of code, i strive to make the web a beautiful place.

Leave a Reply