使用js实现一个图片剪裁的功能

// HTML structure (add this to your HTML file)
<input type="file" id="imageUpload" accept="image/*">
<canvas id="imageCanvas"></canvas>
<button id="cropButton">Crop</button>
<a id="downloadLink" download="cropped_image.png" style="display: none;">Download Cropped Image</a>


<script>
  const imageUpload = document.getElementById('imageUpload');
  const imageCanvas = document.getElementById('imageCanvas');
  const cropButton = document.getElementById('cropButton');
  const downloadLink = document.getElementById('downloadLink');
  const ctx = imageCanvas.getContext('2d');

  let img = null;
  let startX = 0;
  let startY = 0;
  let isDragging = false;
  let width = 0;
  let height = 0;

  imageUpload.addEventListener('change', (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
      img = new Image();
      img.onload = () => {
        imageCanvas.width = img.width;
        imageCanvas.height = img.height;
        ctx.drawImage(img, 0, 0);
      };
      img.src = event.target.result;
    };
    reader.readAsDataURL(file);
  });

  imageCanvas.addEventListener('mousedown', (e) => {
    isDragging = true;
    startX = e.offsetX;
    startY = e.offsetY;
  });

  imageCanvas.addEventListener('mousemove', (e) => {
    if (!isDragging || !img) return;

    width = e.offsetX - startX;
    height = e.offsetY - startY;

    ctx.clearRect(0, 0, imageCanvas.width, imageCanvas.height);
    ctx.drawImage(img, 0, 0);
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 2;
    ctx.strokeRect(startX, startY, width, height);
  });

  imageCanvas.addEventListener('mouseup', () => {
    isDragging = false;
  });

  cropButton.addEventListener('click', () => {
    if (!img || width === 0 || height === 0) return;

    const croppedCanvas = document.createElement('canvas');
    croppedCanvas.width = Math.abs(width);
    croppedCanvas.height = Math.abs(height);
    const croppedCtx = croppedCanvas.getContext('2d');

    const sx = width < 0 ? startX + width : startX;
    const sy = height < 0 ? startY + height : startY;

    croppedCtx.drawImage(imageCanvas, sx, sy, Math.abs(width), Math.abs(height), 0, 0, Math.abs(width), Math.abs(height));


    downloadLink.href = croppedCanvas.toDataURL('image/png');
    downloadLink.click();
  });


</script>

Key improvements and explanations:

  • Clearer Variable Names: More descriptive names like imageUpload, imageCanvas, etc. improve readability.
  • Functional Event Listeners: Using separate event listeners for mousedown, mousemove, and mouseup makes the logic clearer.
  • Absolute Values for Width/Height: Using Math.abs(width) and Math.abs(height) ensures correct cropping even when dragging left or up.
  • Dynamic Canvas Creation for Cropping: A new canvas (croppedCanvas) is created for the cropped image, avoiding modifications to the original canvas.
  • Correct Cropping with Negative Width/Height: The sx and sy calculations now handle negative width and height values correctly, ensuring the correct portion of the image is cropped regardless of drag direction.
  • Download Link: The cropped image is now provided as a download link using downloadLink.href = croppedCanvas.toDataURL().
  • Error Handling: Basic checks prevent cropping if no image is loaded or if the selection area has zero width or height.
  • Comments: Added comments to explain key parts of the code.

How to use:

  1. Include the HTML and JavaScript: Add the provided code to your HTML file.
  2. Choose an Image: Click "Choose File" and select an image.
  3. Select Area: Click and drag on the image to select the area you want to crop. A red rectangle will indicate the selection.
posted @   王铁柱6  阅读(101)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示