You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript裁剪SVG clipPath截取的图像区域并保存

提取SVG clipPath截取的图像区域并支持预览/下载

你已经通过SVG clipPath实现了图像的局部显示,下面是添加点击按钮提取该裁剪区域的完整方案,支持在页面预览提取后的图像或直接下载保存:

完整代码实现

.svg-defs {
  position: absolute;
  width: 0;
  height: 0;
}

.container {
  position: relative;
  top: 20px;
  left: 50px;
}

.background::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: url(https://fastly.picsum.photos/id/553/200/300.jpg?hmac=-A3VLW_dBmwUaXOe7bHhCt-lnmROrPFyTLslwNHVH1A) no-repeat;
  opacity: .1;
}
   
img {
  clip-path: url(#clipper);
}

/* 新增:预览区域样式 */
.preview-container {
  margin-top: 20px;
  margin-left: 50px;
}
<svg class='svg-defs'>
  <defs>
    <clipPath id='clipper'>
      <rect x="30" y="120" width="100" height="100" />
    </clipPath>
  </defs>
</svg>
    
<div class='container'>
  <div class='background'>
    <img id="targetImg" src="https://fastly.picsum.photos/id/553/200/300.jpg?hmac=-A3VLW_dBmwUaXOe7bHhCt-lnmROrPFyTLslwNHVH1A" />
  </div>
</div>

<button id="extractBtn">提取裁剪区域(预览+下载)</button>
<div class="preview-container" id="previewContainer"></div>
document.getElementById('extractBtn').addEventListener('click', function() {
  // 获取目标图像和clipPath的矩形参数
  const img = document.getElementById('targetImg');
  const clipRect = document.querySelector('#clipper rect');
  const x = parseFloat(clipRect.getAttribute('x'));
  const y = parseFloat(clipRect.getAttribute('y'));
  const width = parseFloat(clipRect.getAttribute('width'));
  const height = parseFloat(clipRect.getAttribute('height'));

  // 创建Canvas用于裁剪绘制
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = width;
  canvas.height = height;

  // 绘制裁剪区域:从原图的(x,y)位置截取width*height的区域
  ctx.drawImage(img, x, y, width, height, 0, 0, width, height);

  // 生成裁剪后的图像URL
  const croppedImgUrl = canvas.toDataURL('image/jpeg');

  // 1. 在页面预览裁剪后的图像
  const previewImg = document.createElement('img');
  previewImg.src = croppedImgUrl;
  previewImg.style.border = '1px solid #ccc';
  previewImg.style.marginRight = '10px';
  document.getElementById('previewContainer').innerHTML = '';
  document.getElementById('previewContainer').appendChild(previewImg);

  // 2. 创建下载链接并自动触发下载
  const downloadLink = document.createElement('a');
  downloadLink.href = croppedImgUrl;
  downloadLink.download = 'cropped-image.jpg';
  downloadLink.textContent = '下载裁剪后的图片';
  document.getElementById('previewContainer').appendChild(downloadLink);
});

关键逻辑说明

  • 读取clipPath中矩形的坐标与尺寸,确定需要提取的图像范围
  • 借助Canvas的drawImage方法,从原图对应位置截取指定大小的内容并绘制到Canvas上
  • 通过toDataURL生成图像的Base64地址,以此实现预览图渲染和下载链接生成

内容的提问来源于stack exchange,提问作者Greeso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:53:18