图像资源处理

    mpx提供了对小程序中各种资源加载方式进行处理。

    本文会从使用的角度出发,介绍小程序既有的对图像资源的限制,以及是如何解决这些问题。


    小程序原生支持在wxsswxml中使用线上资源,这点和开发web应用没有太多区别。

    无需任何配置,就可以直接在.mpx中引用线上资源。

    webpack.config.js

    index.mpx

    1. <template>
    2. <view>
    3. <image src='http://my.cdn.com/bg2.png'/>
    4. <view class="container"></view>
    5. <view>
    6. </template>
    7. <style lang="css">
    8. .container: {
    9. background-image: url('http://my.cdn.com/bg1.png');
    10. }
    11. </style>

    • <style>中使用本地资源

      小程序不支持在.wxss的样式中使用本地资源,因此@mpxjs/url-loader会对<style>中的图片做强制base64

      1. webpackconfig = {
      2. module: {
      3. rules: [
      4. {
      5. test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
      6. loader: '@mpxjs/url-loader',
      7. options: /* 强制转换,所以options不做限制 */
      8. }
      9. ]
      10. }
      11. }

      index.mpx

    • <image>组件src属性使用本地资源

      小程序既可以用路径方式引用本地图片资源,也可以用base64进行内联

      设置@mpxjs/url-loaderlimit,资源体积超过limit的做打包处理

      webpack.config.js

      1. webpackconfig = {
      2. module: {
      3. rules: [
      4. test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
      5. options: {
      6. limit: 10000,
      7. name: 'img/[name].[ext]'
      8. }
      9. }
      10. ]
      11. }
      12. }

      index.mpx

      1. <template>
      2. <view>
      3. <image src='./bg2.png'/>
      4. <view>
      5. </template>
    • <cover-image>组件src属性使用本地资源

      可以在资源地址后面加上查询字符串?fallback禁止base64

      webpack.config.js

      index.mpx

      1. <template>
      2. <view>
      3. <cover-image src='./bg2.png?fallback'/>
      4. <view>
      5. </template>

    利用@mpxjs/url-loader,配合mpx提供的计算属性,实现在运行阶段动态设置图片

    文件目录

    1. component
    2. │-- index.mpx
    3. │-- dark.png
    4. │-- light.png

    webpack.config.js

    index.mpx

    1. <template>
    2. <view>
    3. <image src='{{dynamicSrc}}'/>
    4. <view class="container" style='{{dynamicStyle}}'>i have a background image</view>
    5. <button bindtap="clickHandler">click me to change</button>
    6. </view>
    7. </template>
    8. <script>
    9. // 如果是有限张图片
    10. import dark from './dark.png'
    11. import light from './light.png'
    12. createPage({
    13. data: {
    14. count: 0,
    15. imageId: '1'
    16. },
    17. computed: {
    18. dynamicSrc() {
    19. return (this.count % 2 === 0) ? dark : light
    20. },
    21. dynamicStyle() {
    22. let url = (this.count % 2 !== 0) ? dark : light
    23. return `background-image: url(${url})`
    24. },
    25. background () {
    26. // 如果期望整个bgs文件夹里的图片都被纳入
    27. return require('./bgs/' + this.imageId + '.jpg')
    28. }
    29. },
    30. methods: {
    31. clickHandler() {
    32. this.count++
    33. }
    34. }
    35. })
    36. </script>
    37. <style lang="stylus">
    38. .container
    39. </style>

    通过点击button,两个元素的图片会动态变化