mpvue实现仿喜马拉雅banner颜色渐变效果

22 篇文章 0 订阅
2 篇文章 0 订阅

参考:https://blog.csdn.net/WeiHan_Seven/article/details/103872499在这里插入图片描述
用swiper轮播图片,调用色彩分析插件取出图片的配色,然后设置轮播图背景渐进色。
下面的Vue文件是效果实现,底下的两个js是用到的两个工具类:ColorThief、rgb颜色转换成16进制颜色

缺点:没有处理两个轮播图中间的过渡效果

<template>
  <div class="lnk-page">
    <div class="lnk-content">
      <div class="carousel-box" :style="{background: 'linear-gradient(to bottom,' + colors[0]+ ' 0%,' +colors[1] + ' 100%)'}">
        <swiper class="swiper"
                indicator-dots="indicatorDots"
                indicator-color="indicatorColor"
                indicator-active-color="#FFFFFF"
                autoplay='autoPlay'
                circular="circular"
                interval="5000"
                @change="changeSwiper"
                :current="currentIndex">
          <block v-for="(item, index) in memberShopSwiperList" :key="index">
            <swiper-item >
              <img class="carousel-img" :src="item.imgUrl" lazy-load="true" mode="scaleToFill"/>
            </swiper-item>
          </block>
        </swiper>
      </div>
      <canvas  id='image-handler' style="width:350px; height:300px;position: absolute;top: 99999px" canvas-id="imageHandler"></canvas>
      <div class="color-box" style="width: 500px; height: 50px">
        <div class="color-item" v-for="(citem, cindex) in colors" :key="cindex" :style="{backgroundColor: citem}" style="width: 50px;height:50px;"></div>
      </div>
    </div>

  </div>
</template>
<script>
  import ColorThief from '../../utils/colors/color-thief.js'
  import {
    rgbToHex
  } from '../../utils/colors/util.js'
  export default {
    data () {
      return {
        currentIndex: 0,
        memberShopSwiperList: [
          {
            imgUrl: 'http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201908/jiaoben6983/images/1.jpg'
          },
          {
            imgUrl: 'http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201908/jiaoben6983/images/4.jpg'
          },
          {
            imgUrl: 'http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201908/jiaoben6983/images/5.jpg'
          },
          {
            imgUrl: 'http://demo.sc.chinaz.net/Files/DownLoad/webjs1/201908/jiaoben6983/images/2.jpg'
          }
        ],
        screenWidth: 350,
        colorThief: '',
        imgPath: 'cloud://nopc.6e6f-norm6pc-1300924598/meinv/00010.jpg',
        colors: [
        ],
        imgInfo: {},
        colorCount: 5
      }
    },
    onLoad () {
      this.changeFn()
    },
    onShow () {

    },
    methods: {
      changeSwiper (e) {
        this.currentIndex = e.target.current
        this.changeFn(this.memberShopSwiperList[this.currentIndex].imgUrl)
      },
      changeFn (item) {
        let that = this
        that.colorThief =  new ColorThief('imageHandler')
        let img = ''
        if (item) {
          img = item
        } else {
          img = that.memberShopSwiperList[0].imgUrl
        }
        wx.getImageInfo({
          src: img,
          success: (imgInfo) => {
            let width = 350
            let height = 300
            let imgPath = imgInfo.path
            let scale = 0.8 * that.screenWidth / Math.max(width, height)
            let canvasWidth = Math.floor(scale * width)
            let canvasHeight = Math.floor(scale * height)
            that.canvasScale = scale
            that.imgPath = imgPath
            that.canvasWidth = canvasWidth
            that.canvasHeight = canvasHeight
            let quality = 1
            that.colorThief.getPalette({
              width: canvasWidth,
              height: canvasHeight,
              imgPath: that.imgPath,
              colorCount: that.colorCount,
              quality
            }, (colors) => {
              if (colors) {
                colors = colors.map((color) => {
                  console.log(('#' + rgbToHex(color[0], color[1], color[2])))
                  return ('#' + rgbToHex(color[0], color[1], color[2]))
                })
                that.colors = colors
                that.$set.colors = colors
              }
            })
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
.lnk-page{
  .lnk-content{
    width: 100vw;
    height: 100vh;
    position: relative;
    text-align: center;
    overflow: hidden;
    .carousel-box {
      width: 100%;
      height: 262px;
      position: relative;
      border-bottom-left-radius: 30%;
      border-bottom-right-radius: 30%;

      .swiper {
        width: 92%;
        height: 160px;
        position: absolute;
        top: 32px;
        left: 4%;
        right: 4%;
        margin: 0 auto;

        .carousel-img {
          width: 100%;
          height: 100%;
          border-radius: 5px;
        }
      }
    }
    .color-box{
      margin-top: 50px;
      @include flex;
      .color-item{

      }
    }
  }
}
</style>

里面的插件是ColorThief的工具类,

class ColorThief {
  constructor (canvasID) {
    this.canvasID = canvasID
  }
  getPalette = ({width, height, imgPath, colorCount, quality}, cb) => {
    if (typeof colorCount === 'undefined' || colorCount < 2 || colorCount > 256) {
      colorCount = 10
    }
    if (typeof quality === 'undefined' || quality < 1) {
      quality = 10
    }
    let ctx = wx.createCanvasContext(this.canvasID)
    console.log('ctx', ctx)
    ctx.drawImage(imgPath, 0, 0, width, height)
    // ctx.clearRect(0,0,width,height);
    ctx.draw(false, () => {
      console.log('draw end')
      wx.canvasGetImageData({
        canvasId: this.canvasID,
        x: 0,
        y: 0,
        width: width,
        height: height,
        success (res) {
          console.log('getImgData', res)
          console.log(res.width) // 100
          console.log(res.height) // 100
          console.log(res.data instanceof Uint8ClampedArray) // true
          console.log(res.data.length) // 100 * 100 * 4
          var pixels = res.data
          var pixelCount = width * height
          var pixelArray = []
          for (var i = 0, offset, r, g, b, a; i < pixelCount; i = i + quality) {
            offset = i * 4
            r = pixels[offset + 0]
            g = pixels[offset + 1]
            b = pixels[offset + 2]
            a = pixels[offset + 3]
            // If pixel is mostly opaque and not white
            if (a >= 125) {
              if (!(r > 250 && g > 250 && b > 250)) {
                pixelArray.push([r, g, b])
              }
            }
          }
          console.log('valid pixel:', pixelArray.length)
          var cmap = MMCQ.quantize(pixelArray, colorCount)
          var palette = cmap ? cmap.palette() : null
          console.log(palette)
          cb(palette)
        }
      })
    })
  };
}

/*!
 * quantize.js Copyright 2008 Nick Rabinowitz.
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 * @license
 */

// fill out a couple protovis dependencies
/*!
 * Block below copied from Protovis: http://mbostock.github.com/protovis/
 * Copyright 2010 Stanford Visualization Group
 * Licensed under the BSD License: http://www.opensource.org/licenses/bsd-license.php
 * @license
 */
var pv = {
  map: function (array, f) {
    var o = {}
    return f ? array.map(function (d, i) { o.index = i; return f.call(o, d) }) : array.slice()
  },
  naturalOrder: function (a, b) {
    return (a < b) ? -1 : ((a > b) ? 1 : 0)
  },
  sum: function (array, f) {
    var o = {}
    return array.reduce(f ? function (p, d, i) { o.index = i; return p + f.call(o, d) } : function (p, d) { return p + d }, 0)
  },
  max: function (array, f) {
    return Math.max.apply(null, f ? pv.map(array, f) : array)
  }
}

/**
 * Basic Javascript port of the MMCQ (modified median cut quantization)
 * algorithm from the Leptonica library (http://www.leptonica.com/).
 * Returns a color map you can use to map original pixels to the reduced
 * palette. Still a work in progress.
 *
 * @author Nick Rabinowitz
 * @example

// array of pixels as [R,G,B] arrays
var myPixels = [[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207]
                // etc
                ];
var maxColors = 4;

var cmap = MMCQ.quantize(myPixels, maxColors);
var newPalette = cmap.palette();
var newPixels = myPixels.map(function(p) {
    return cmap.map(p);
});

 */
export const MMCQ = (function () {
  // private constants
  let sigbits = 5
  let  rshift = 8 - sigbits
  let maxIterations = 1000
  let fractByPopulations = 0.75

  // get reduced-space color index for a pixel
  function getColorIndex (r, g, b) {
    return (r << (2 * sigbits)) + (g << sigbits) + b
  }

  // Simple priority queue
  function PQueue (comparator) {
    let contents = []
    let sorted = false

    function sort () {
      contents.sort(comparator)
      sorted = true
    }

    return {
      push: function (o) {
        contents.push(o)
        sorted = false
      },
      peek: function (index) {
        if (!sorted) sort()
        if (index === undefined) index = contents.length - 1
        return contents[index]
      },
      pop: function () {
        if (!sorted) sort()
        return contents.pop()
      },
      size: function () {
        return contents.length
      },
      map: function (f) {
        return contents.map(f)
      },
      debug: function () {
        if (!sorted) sort()
        return contents
      }
    }
  }

  // 3d color space box
  function VBox (r1, r2, g1, g2, b1, b2, histo) {
    var vbox = this
    vbox.r1 = r1
    vbox.r2 = r2
    vbox.g1 = g1
    vbox.g2 = g2
    vbox.b1 = b1
    vbox.b2 = b2
    vbox.histo = histo
  }
  VBox.prototype = {
    volume: function (force) {
      var vbox = this
      if (!vbox._volume || force) {
        vbox._volume = ((vbox.r2 - vbox.r1 + 1) * (vbox.g2 - vbox.g1 + 1) * (vbox.b2 - vbox.b1 + 1))
      }
      return vbox._volume
    },
    count: function (force) {
      let vbox = this
      let histo = vbox.histo
      if (!vbox._count_set || force) {
        let npix = 0
        let index, i, j, k
        for (i = vbox.r1; i <= vbox.r2; i++) {
          for (j = vbox.g1; j <= vbox.g2; j++) {
            for (k = vbox.b1; k <= vbox.b2; k++) {
              index = getColorIndex(i, j, k)
              npix += (histo[index] || 0)
            }
          }
        }
        vbox._count = npix
        vbox._count_set = true
      }
      return vbox._count
    },
    copy: function () {
      var vbox = this
      return new VBox(vbox.r1, vbox.r2, vbox.g1, vbox.g2, vbox.b1, vbox.b2, vbox.histo)
    },
    avg: function (force) {
      let vbox = this
      let histo = vbox.histo
      if (!vbox._avg || force) {
        let ntot = 0
        let  mult = 1 << (8 - sigbits)
        let rsum = 0
        let gsum = 0
        let bsum = 0
        let hval, i, j, k, histoindex
        for (i = vbox.r1; i <= vbox.r2; i++) {
          for (j = vbox.g1; j <= vbox.g2; j++) {
            for (k = vbox.b1; k <= vbox.b2; k++) {
              histoindex = getColorIndex(i, j, k)
              hval = histo[histoindex] || 0
              ntot += hval
              rsum += (hval * (i + 0.5) * mult)
              gsum += (hval * (j + 0.5) * mult)
              bsum += (hval * (k + 0.5) * mult)
            }
          }
        }
        if (ntot) {
          vbox._avg = [~~(rsum / ntot), ~~(gsum / ntot), ~~(bsum / ntot)]
        } else {
          //                    console.log('empty box');
          vbox._avg = [
            ~~(mult * (vbox.r1 + vbox.r2 + 1) / 2),
            ~~(mult * (vbox.g1 + vbox.g2 + 1) / 2),
            ~~(mult * (vbox.b1 + vbox.b2 + 1) / 2)
          ]
        }
      }
      return vbox._avg
    },
    contains: function (pixel) {
      let vbox = this
      let rval = pixel[0] >> rshift
      let gval = pixel[1] >> rshift
      let bval = pixel[2] >> rshift
      return (rval >= vbox.r1 && rval <= vbox.r2 &&
        gval >= vbox.g1 && gval <= vbox.g2 &&
        bval >= vbox.b1 && bval <= vbox.b2)
    }
  }

  // Color map
  function CMap () {
    this.vboxes = new PQueue(function (a, b) {
      return pv.naturalOrder(
        a.vbox.count() * a.vbox.volume(),
        b.vbox.count() * b.vbox.volume()
      )
    })
  }
  CMap.prototype = {
    push: function (vbox) {
      this.vboxes.push({
        vbox: vbox,
        color: vbox.avg()
      })
    },
    palette: function () {
      return this.vboxes.map(function (vb) { return vb.color })
    },
    size: function () {
      return this.vboxes.size()
    },
    map: function (color) {
      var vboxes = this.vboxes
      for (var i = 0; i < vboxes.size(); i++) {
        if (vboxes.peek(i).vbox.contains(color)) {
          return vboxes.peek(i).color
        }
      }
      return this.nearest(color)
    },
    nearest: function (color) {
      let vboxes = this.vboxes
      let  d1, d2, pColor
      for (var i = 0; i < vboxes.size(); i++) {
        d2 = Math.sqrt(
          Math.pow(color[0] - vboxes.peek(i).color[0], 2) +
          Math.pow(color[1] - vboxes.peek(i).color[1], 2) +
          Math.pow(color[2] - vboxes.peek(i).color[2], 2)
        )
        if (d2 < d1 || d1 === undefined) {
          d1 = d2
          pColor = vboxes.peek(i).color
        }
      }
      return pColor
    },
    forcebw: function () {
      // XXX: won't  work yet
      var vboxes = this.vboxes
      vboxes.sort(function (a, b) { return pv.naturalOrder(pv.sum(a.color), pv.sum(b.color)) })

      // force darkest color to black if everything < 5
      var lowest = vboxes[0].color
      if (lowest[0] < 5 && lowest[1] < 5 && lowest[2] < 5) { vboxes[0].color = [0, 0, 0] }

      // force lightest color to white if everything > 251
      let idx = vboxes.length - 1
      let highest = vboxes[idx].color
      if (highest[0] > 251 && highest[1] > 251 && highest[2] > 251) { vboxes[idx].color = [255, 255, 255] }
    }
  }

  // histo (1-d array, giving the number of pixels in
  // each quantized region of color space), or null on error
  function getHisto (pixels) {
    let histosize = 1 << (3 * sigbits)
    let histo = new Array(histosize)
    let index, rval, gval, bval
    pixels.forEach(function (pixel) {
      rval = pixel[0] >> rshift
      gval = pixel[1] >> rshift
      bval = pixel[2] >> rshift
      index = getColorIndex(rval, gval, bval)
      histo[index] = (histo[index] || 0) + 1
    })
    return histo
  }

  function vboxFromPixels (pixels, histo) {
    let rmin = 1000000
    let  rmax = 0
    let gmin = 1000000
    let gmax = 0
    let bmin = 1000000
    let bmax = 0
    let  rval, gval, bval
    // find min/max
    pixels.forEach(function (pixel) {
      rval = pixel[0] >> rshift
      gval = pixel[1] >> rshift
      bval = pixel[2] >> rshift
      if (rval < rmin) rmin = rval
      else if (rval > rmax) rmax = rval
      if (gval < gmin) gmin = gval
      else if (gval > gmax) gmax = gval
      if (bval < bmin) bmin = bval
      else if (bval > bmax) bmax = bval
    })
    return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo)
  }

  function medianCutApply (histo, vbox) {
    if (!vbox.count()) return

    let rw = vbox.r2 - vbox.r1 + 1
    let  gw = vbox.g2 - vbox.g1 + 1
    let  bw = vbox.b2 - vbox.b1 + 1
    let maxw = pv.max([rw, gw, bw])
    // only one pixel, no split
    if (vbox.count() === 1) {
      return [vbox.copy()]
    }
    /* Find the partial sum arrays along the selected axis. */
    let total = 0
    let partialsum = []
    let lookaheadsum = []
    let  i, j, k, sum, index
    if (maxw === rw) {
      for (i = vbox.r1; i <= vbox.r2; i++) {
        sum = 0
        for (j = vbox.g1; j <= vbox.g2; j++) {
          for (k = vbox.b1; k <= vbox.b2; k++) {
            index = getColorIndex(i, j, k)
            sum += (histo[index] || 0)
          }
        }
        total += sum
        partialsum[i] = total
      }
    } else if (maxw === gw) {
      for (i = vbox.g1; i <= vbox.g2; i++) {
        sum = 0
        for (j = vbox.r1; j <= vbox.r2; j++) {
          for (k = vbox.b1; k <= vbox.b2; k++) {
            index = getColorIndex(j, i, k)
            sum += (histo[index] || 0)
          }
        }
        total += sum
        partialsum[i] = total
      }
    } else {  /* maxw == bw */
      for (i = vbox.b1; i <= vbox.b2; i++) {
        sum = 0
        for (j = vbox.r1; j <= vbox.r2; j++) {
          for (k = vbox.g1; k <= vbox.g2; k++) {
            index = getColorIndex(j, k, i)
            sum += (histo[index] || 0)
          }
        }
        total += sum
        partialsum[i] = total
      }
    }
    partialsum.forEach(function (d, i) {
      lookaheadsum[i] = total - d
    })
    function doCut (color) {
      let dim1 = color + '1'
      let  dim2 = color + '2'
      let  left, right, vbox1, vbox2, d2
      let count2 = 0
      for (i = vbox[dim1]; i <= vbox[dim2]; i++) {
        if (partialsum[i] > total / 2) {
          vbox1 = vbox.copy()
          vbox2 = vbox.copy()
          left = i - vbox[dim1]
          right = vbox[dim2] - i
          if (left <= right) { d2 = Math.min(vbox[dim2] - 1, ~~(i + right / 2)) } else d2 = Math.max(vbox[dim1], ~~(i - 1 - left / 2))
          // avoid 0-count boxes
          while (!partialsum[d2]) d2++
          count2 = lookaheadsum[d2]
          while (!count2 && partialsum[d2 - 1]) count2 = lookaheadsum[--d2]
          // set dimensions
          vbox1[dim2] = d2
          vbox2[dim1] = vbox1[dim2] + 1
          //                    console.log('vbox counts:', vbox.count(), vbox1.count(), vbox2.count());
          return [vbox1, vbox2]
        }
      }
    }
    // determine the cut planes
    return maxw === rw ? doCut('r')
      : maxw === gw ? doCut('g')
        : doCut('b')
  }

  function quantize (pixels, maxcolors) {
    // short-circuit
    if (!pixels.length || maxcolors < 2 || maxcolors > 256) {
      //            console.log('wrong number of maxcolors');
      return false
    }

    // XXX: check color content and convert to grayscale if insufficient

    let histo = getHisto(pixels)
    // let histosize = 1 << (3 * sigbits)

    // check that we aren't below maxcolors already
    let nColors = 0
    histo.forEach(function () { nColors++ })
    if (nColors <= maxcolors) {
      // XXX: generate the new colors from the histo and return
    }

    // get the beginning vbox from the colors
    let vbox = vboxFromPixels(pixels, histo)
    let  pq = new PQueue(function (a, b) { return pv.naturalOrder(a.count(), b.count()) })
    pq.push(vbox)

    // inner function to do the iteration
    function iter (lh, target) {
      let ncolors = 1
      let niters = 0
      let vbox
      while (niters < maxIterations) {
        vbox = lh.pop()
        if (!vbox.count()) { /* just put it back */
          lh.push(vbox)
          niters++
          continue
        }
        // do the cut
        let vboxes = medianCutApply(histo, vbox)
        let vbox1 = vboxes[0]
        let vbox2 = vboxes[1]

        if (!vbox1) {
          //                    console.log("vbox1 not defined; shouldn't happen!");
          return
        }
        lh.push(vbox1)
        if (vbox2) {  /* vbox2 can be null */
          lh.push(vbox2)
          ncolors++
        }
        if (ncolors >= target) return
        if (niters++ > maxIterations) {
          //                    console.log("infinite loop; perhaps too few pixels!");
          return
        }
      }
    }

    // first set of colors, sorted by population
    iter(pq, fractByPopulations * maxcolors)

    // Re-sort by the product of pixel occupancy times the size in color space.
    var pq2 = new PQueue(function (a, b) {
      return pv.naturalOrder(a.count() * a.volume(), b.count() * b.volume())
    })
    while (pq.size()) {
      pq2.push(pq.pop())
    }

    // next set - generate the median cuts using the (npix * vol) sorting.
    iter(pq2, maxcolors - pq2.size())

    // calculate the actual colors
    var cmap = new CMap()
    while (pq2.size()) {
      cmap.push(pq2.pop())
    }

    return cmap
  }

  return {
    quantize: quantize
  }
})()

export default ColorThief

将返回的rgb颜色转换成16进制颜色工具类

export function rgbToHex (R, G, B) { return toHex(R) + toHex(G) + toHex(B) }
export function toHex (n) {
  n = parseInt(n, 10)
  if (isNaN(n)) return '00'
  n = Math.max(0, Math.min(n, 255))
  return '0123456789ABCDEF'.charAt((n - n % 16) / 16) +
    '0123456789ABCDEF'.charAt(n % 16)
}
export function hexToRgb (hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null
}
export function genUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0
    let v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}
export function colorsEqual (colors1, colors2) {
  if (colors1.length !== colors2.length) {
    return false
  }
  for (let i = 0; i < colors1.length; i++) {
    if (colors1[i] !== colors2[i]) {
      return false
    }
  }
  return true
}
export function saveBlendent ({colors, uuid}) {
  let data = wx.getStorageSync('colors') || []
  if (!uuid) {
    for (let i = 0; i < data.length; i++) {
      let blendent = data[i]
      if (colorsEqual(blendent.colors, colors)) {
        data.splice(i, 1)
      }
    }
    data.unshift({
      uuid: genUUID(),
      colors: colors
    })
  } else {
    let index = data.findIndex((blendent) => blendent.uuid === uuid)
    let blendent = data[index]
    blendent.colors = colors
    data.splice(index, 1)
    data.unshift(blendent)
  }
  wx.setStorage({
    key: 'colors',
    data: data,
    complete: () => {
      console.log('save complete')
      wx.showToast({
        title: '保存成功!',
        icon: 'success'
      })
    }
  })
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值