小程序进阶-emoji表情

一、简介

小程序如何发送表情,微信小程序官方文档“扩展能力”为我们提供了emoji组件,即仿微信表情组件。
在这里插入图片描述

二、开发流程

(1)npm方式构建

//初始化项目,在node开发中使用npm init会生成一个pakeage.json文件,
//这个文件主要是用来记录这个项目的详细信息的,它会将我们在项目开发中所要用到的包,
//以及项目的详细信息等记录在这个项目中。
 - npm init 或 npm init -y
//安装生产环境
 - npm install --production
//安装vant,Vant Weapp 是移动端 Vue 组件库 Vant 的小程序版本,
//两者基于相同的视觉规范,提供一致的 API 接口,助力开发者快速搭建小程序应用。
 - npm i vant-weapp -S --production
//安装emoji
 - npm install @miniprogram-component-plus/emoji
 - 微信开发工具-->工具-->构建npm
 -  page.json引入组件:
{
    
    
    "usingComponents": {
    
    
        "mp-emoji": "@miniprogram-component-plus/emoji"
    }
}

在这里插入图片描述
(2)直接从官方组件库源码拷贝,使用方法同上。
在这里插入图片描述
(3)官方演示
在这里插入图片描述
在这里插入图片描述
(4)源码分析

  • 组件选择器,创建emoji实例

    const emojiInstance = this.selectComponent('.mp-emoji')
    //表情中文列表
    this.emojiNames = emojiInstance.getEmojiNames()
    //parseEmoji 解析函数
    this.parseEmoji = emojiInstance.parseEmoji
    
  • 组件渲染
    hidden控制元素显示,mp-emoji引用组件,source指定雪碧图地址,bindinsertemoji点击表情获取表情文本如“[微笑]”,binddelemoji实现删除键,bindsend实现发送键。

    <view class="reply_panel {
           
           {emojiShow ? 'show': ''}}" hidden="{
           
           {!emojiShow}}">
          <mp-emoji source="{
           
           {emojiSource}}" class="mp-emoji" bindinsertemoji="insertEmoji" binddelemoji="deleteEmoji" bindsend="onsend"></mp-emoji>
    </view>
    
  • 文本解析

    const = comment = '啊的四个[微笑]撒地方'
    //文本解析,type为1代表普通文本,2为表情,并给出imageClass样式。
    const parsedCommnet = parseEmoji(comment)
    [
      {
          
          type: 1, content: '啊的四个'},
      {
          
          type: 2, content: '[微笑]', imageClass: 'smiley_4'},
      {
          
          type: 1, content: '撒地方'},
    ]
    
  • 文本输出
    js将文本解析后输出数组,我们循环该数组。根据type属性判断文本类型,为1普通输出,为2根据imageClass指定表情图片样式。显示原理:background-image指定view元素背景视图,background-position: -66px -264px设置背景图像的起始位置,transform-origin: 0 0设置视图转换的基点,transform: scale(height/64)设置表情缩放比例。背景图片表情的尺寸为64px。

    <view class="comment">
        <block wx:for="{
           
           {parsedComment}}" wx:key="item">
          <block wx:if="{
           
           {item.type === 1}}">{
         
         {item.content}}</block>
          <view 
            wx:if="{
           
           {item.type === 2}}" 
            style="display: inline-block; width: {
             
             {
             
             lineHeight}}px; height: {
             
             {
             
             lineHeight}}px">
            <view 
              class="{
           
           {item.imageClass}}"
              style="background-image: url({
             
             {emojiSource}});transform-origin: 0 0; transform: scale({
             
             {
             
             lineHeight / 64}});"></view>
          </view>
        </block>
    </view>
    

    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43166227/article/details/115399800
今日推荐