Vue2组件、功能插件实例运用 - vue-cropper(裁剪成 图形 图片)


问题起因

vue-cropper插件提供了非常好的图片裁剪功能,但美中不足的是,只能裁剪出长方形、正方形的图片,不能裁剪出其他图形的图片,尤其是圆形图片。
虽然可以先裁剪成正方形图片,然后给图片显示区域设置样式 border-radius: 50% 以达到显示成圆形的效果,但这抵不住一些产品,人家就要求裁剪成圆形图片,你这种方式就行不通了。

本文承接  继续。

1、重写图片裁剪弹出窗组件

1.1 template模板:

<template>
  
  <div class="el-col el-col-24">
    <div class="cropper-w">
      <div class="cropper text-align-c" :class="graphicsState === 'square' ? '' : 'circular-w'">
        <VueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :info="option.info"
          :full="option.full"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :fixed="option.fixed"
          :fixedNumber="option.fixedNumber"
          :centerBox="option.centerBox"
          :infoTrue="option.infoTrue"
          :autoCropWidth="option.autoCropWidth ? option.autoCropWidth : 0"
          :autoCropHeight="option.autoCropHeight ? option.autoCropHeight : 0"
          :fixedBox="option.fixedBox"
        >VueCropper>
      div>
    div>
    <div class="el-col el-col-24 flex-layout btn-w">
      <el-button type="success" @click.stop="rotateLeft">向左旋转el-button>
      <el-button type="info" @click.stop="rotateRight">向右旋转el-button>
      <el-button type="primary" @click.stop="getCropData">获取base64数据el-button>
      <el-button type="primary" @click.stop="getCropBlob">获取blob数据el-button>
    div>
  div>
template>

1.2 配套样式:

1.3 组件引用及功能函数:

2、问题处理

2.1 图片裁剪完成后圆形区域以外的四个角,透明区域变成了黑色背景或纯白色背景

  这是因为 在canvas开始绘制之前 没有设置背景色或者设置了纯白色背景色,但没有设置透明度造成的。

解决方法:在canvas开始绘制前 设置白色填充色,并将透明度设置为0。

const canvas = document.createElement('canvas')
const width = image.width
const height = image.height
canvas.width = width
canvas.height = height
const context = canvas.getContext('2d')
context.clearRect(0, 0, width, height)
// 在canvas开始绘制前填充白色背景并设置透明度,用以清除图片裁剪后透明区域变成黑色的问题
context.fillStyle = 'rgba(255, 255, 255, 0)'
context.fillRect(0, 0, width, height)

    注:canvas的 fillStyle属性支持 rgba() 函数

(网页截图)

2.2 设置白色填充色,并将透明度设置为0后,图片四周有白色方形边线

2.3 底图拖动后,截图框裁剪到底图以外的透明区域,绘制成图后 透明区域变成了黑色背景,如下所示:

相关