Home > Web Front-end > JS Tutorial > Implement image cropping function based on JavaScript

Implement image cropping function based on JavaScript

WBOY
Release: 2023-08-09 17:52:45
Original
3778 people have browsed it

Implement image cropping function based on JavaScript

Image cropping function based on JavaScript

With the development of the Internet, pictures have become more and more important in our lives. In web development, we often encounter the need to crop images. This article will implement a simple image cropping function through JavaScript and attach a code example.

1. Technical preparation
Before implementing the image cropping function, we need to prepare the following technologies:

  1. HTML: used to build the page structure.
  2. CSS: used to beautify the page style.
  3. JavaScript: used to implement the image cropping function.
  4. Canvas: used to display images on the page and perform cropping operations.

2. Page layout
First, we need to build a page structure to display pictures and add control buttons for cropping functions. The following is a simple sample code:

<!DOCTYPE html>
<html>
  <head>
    <title>图片剪裁功能</title>
    <style>
      #container {
        width: 800px;
        margin: 0 auto;
        text-align: center;
      }
      canvas {
        border: 1px solid #000;
        margin-bottom: 20px;
      }
      button {
        padding: 10px;
        margin: 10px;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <canvas id="imageCanvas" width="600" height="400"></canvas>
      <button onclick="loadImage()">上传图片</button>
      <button onclick="cropImage()">剪裁图片</button>
    </div>
    <script src="script.js"></script>
  </body>
</html>
Copy after login

In this sample code, we create a container (<div id="container">) to contain images and controls button. The image is displayed through the <canvas> tag (<canvas id="imageCanvas">), and we added a ID to facilitate subsequent JavaScript code operations. 3. JavaScript to implement image cropping function

Next, we need to implement the image uploading and cropping function through JavaScript. The following is a simple sample code:

const imageCanvas = document.getElementById('imageCanvas');
const ctx = imageCanvas.getContext('2d');
let image = null;

function loadImage() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = function(event) {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.onload = function(e) {
      const img = new Image();
      img.onload = function() {
        ctx.clearRect(0, 0, imageCanvas.width, imageCanvas.height);
        ctx.drawImage(img, 0, 0, imageCanvas.width, imageCanvas.height);
        image = img;
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  };
  input.click();
}

function cropImage() {
  if (image) {
    const cropCanvas = document.createElement('canvas');
    const cropCtx = cropCanvas.getContext('2d');
    cropCanvas.width = 400;
    cropCanvas.height = 400;
    cropCtx.drawImage(image, 0, 0, cropCanvas.width, cropCanvas.height);
    const croppedImage = cropCanvas.toDataURL('image/jpeg');
    window.open(croppedImage);
  } else {
    alert('请先上传图片');
  }
}
Copy after login

In this sample code, we obtain the <canvas>

element through document.getElementById('imageCanvas') , and obtain the context object for drawing 2D graphics through imageCanvas.getContext('2d').

loadImage()

function is used to upload images. It is obtained by creating an <input> element, setting its type to file (input.type = 'file'), and listening for the onchange event Image files uploaded by users. Then read the image file uploaded by the user through FileReader and convert it into a URL (reader.readAsDataURL(file)). Then create an <image></image> element, and set its src to the URL just obtained, and then draw this <image></image> element to <canvas>Up.

cropImage()

function is used to crop images. It first determines whether the user has uploaded an image. If an image has been uploaded, we create a new <canvas> element and set the width and height of that element (in this example, we set the width and height to 400). Then draw the original image to the new <canvas> through the drawImage() method, and convert the cropped image into URL. Finally, open a new window to display the cropped image through window.open(). 4. Effect displayOpen the HTML file you just created in the browser, click the "Upload Image" button, and select an image to upload. After that, click the "Crop Image" button and the cropped image will be displayed in a new window.

Through the above steps, we have successfully implemented a simple JavaScript-based image cropping function. You can adjust and expand this function according to your own needs to make it more suitable for actual development needs.

The above is the detailed content of Implement image cropping function based on JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template