小程序開發一個朋友圈熱門的互動答題應用

這是以前受到朋友圈的一些 親密度測試 的啓發,開發的一個互動答題應用。前端

功能

  1. 建立自定義題目,設置正確選項
  2. 生成分享圖邀請好友來答題
  3. 好友獲得成績單,並能夠生成圖片分享
  4. 通知中心能夠查看好友答題記錄

技術棧

  • 前端:小程序
  • 後端:雲開發
  • 框架:mpx

展現

小程序搜索:小題卡。因爲使用免費到雲套餐,接口有訪問次數限制

預覽地址

小題卡.jpg

截圖

應用截圖.jpg

代碼

git倉庫:https://github.com/luosijie/m...node

代碼結構

代碼結構.jpg

示例

因爲完整項目涉及簡單交互較多,下面展現一些主要功能代碼

新建題目

核心要點:用 swipe組件 實現題目到卡片式切換
<template>
  <view>
    <swiper class="cards" bindchange="swiperChange" current="{{ current }}">
      <!-- 全局配置 -->
      <swiper-item>
        <view class="card config">
          <textarea type="text" maxlength="12" auto-height="true" wx:model="{{ formData.title }}"  placeholder="請輸入題卡名稱"/>
        </view>
      </swiper-item>
      <swiper-item wx:for="{{ formData.cards }}" wx:key="id" wx:for-item="card">
        <view class="card">
          <!-- 標題 -->
          <input type="text" maxlength="12" class="title" value="{{ card.title }}" placeholder="請輸入標題" bindblur="titleChange"/>
          <!-- 選項 -->
          <view
            class="option"
            wx:for="{{ card.options }}"
            wx:key="id"
            wx:for-item="option"
            wx:for-index="optionIndex"
          >
            <!-- 移除選項 -->
            <i class="remove iconfont icon-remove" bindtap="removeOption(optionIndex)"></i>
            <!-- 選項標題 -->
            <input type="text" maxlength="12" value="{{ option.value }}" placeholder="請輸入選項標題" bindblur="optionTitleChange(optionIndex, $event)"/>
            <!-- 正確選項 -->
            <view class="correct" bindtap="setCorrect(index, optionIndex)">
              <i class="check iconfont icon-check" wx:if="{{ card.correct === optionIndex }}"></i>
            </view>
          </view>
          <!-- 新增 -->
          <view class="add-option" wx:if="{{ card.options.length < 4 }}" bindtap="addOption">新增選項</view>
        </view>
      </swiper-item>
      <swiper-item>
        <view class="card" bindtap="addCard">
          <view class="new-card">
            <i class="iconfont icon-new-card"></i>
          </view>
        </view>
      </swiper-item>
    </swiper>
    <view class="controls">
      <view class="ps">
        <block wx:if="{{ current < formData.cards.length + 1 && current > 0 }}">
          <view class="tip">
            點擊選項右邊標記正確答案
          </view>
          <i class="delete-card iconfont icon-clear" bindtap="deleteCard" wx:if="{{ current > 1 }}"></i>
        </block>
      </view>
      <view class="swip">
        <view class="pre iconfont icon-pre" bindtap="pre"></view>
        <view class="current">
          <block wx:if="{{ current === 0 }}">
            題卡配置
          </block>
          <block wx:elif="{{ current < formData.cards.length + 1 }}">
            第{{ current }}/{{ formData.cards.length }}題
          </block>
          <block wx:else>
            新增題目
          </block>
        </view>
        <view class="next iconfont icon-next" bindtap="next"></view>
      </view>
      <view class="generate" bindtap="generate">生成</view>
    </view>
  </view>
</template>

<script>
  import { createPage } from '@mpxjs/core'
  createPage({
    data: {
      current: 0,
      formData: {
        title: '',
        cards: []
      }
    },
    onLoad () {
      this.formData.cards = []
      const card = this.generateCard()
      this.formData.cards.push(card)
    },
    methods: {
      // 生成選項
      generateOption (id) {
        return {
          id,
          value: ''
        }
      },
      // 生成一個起始題目
      generateCard () {
        const id = new Date().getTime()
        const card = {
          id,
          title: '',
          options: [
            this.generateOption(id + 1),
            this.generateOption(id + 2),
            this.generateOption(id + 3),
            this.generateOption(id + 4)
          ],
          correct: 0
        }
        return card
      },
      addCard () {
        const card = this.generateCard()
        this.formData.cards.push(card)
      },
      swiperChange (e) {
        this.current = e.detail.current
      },
      // 切換上一題
      pre () {
        if (this.current > 0) {
          this.current--
        }
      },
      // 切換下一題目
      next () {
        if (this.current < this.formData.cards.length + 1) {
          this.current++
          console.log('cards:', this.formData)
        }
      },
      // 移除選項
      removeOption (index) {
        const options = this.formData.cards[this.current - 1].options
        if (options.length < 3) {
          wx.showToast({
            title: '至少保留2個選項',
            icon: 'none'
          })
          return
        }
        options.splice(index, 1)
      },
      // 新增選項
      addOption () {
        const options = this.formData.cards[this.current - 1].options
        const option = this.generateOption(new Date().getTime())
        options.push(option)
      },
      // 刪除卡片
      deleteCard () {
        console.log('delete')
        if (this.formData.cards.length < 2) {
          wx.showToast({
            title: '不能再刪了',
            icon: 'none'
          })
          return
        }
        wx.showModal({
          title: '提示',
          content: '肯定刪除該題目嗎',
          confirmColor: '#40A9FF',
          success: () => {
            this.formData.cards.splice(this.current - 1, 1)
            console.log('刪除卡片', this.formData.cards)
          }
        })
      },
      titleChange (e) {
        this.formData.cards[this.current - 1].title = e.detail.value
        console.log('e', this.formData.cards)
      },
      optionTitleChange (index, e) {
        const options = this.formData.cards[this.current - 1].options
        options[index].value = e.detail.value
      },
      // 校驗題卡表單
      validateForm () {
        if (!this.formData.title) {
          wx.showToast({
            title: '題卡名稱未填寫',
            icon: 'none'
          })
          return false
        }
        for (let i = 0; i < this.formData.cards.length; i++) {
          const card = this.formData.cards[i]
          if (!card.title) {
            wx.showToast({
              title: `第${i + 1}道題 標題未填寫`,
              icon: 'none'
            })
            return false
          }
          // 校驗選項標題填寫狀況
          for (let j = 0; j < card.options.length; j++) {
            const option = card.options[j]
            if (!option.value) {
              wx.showToast({
                title: `第${i + 1}道題 選項未完善`,
                icon: 'none'
              })
              return false
            }
          }
        }
        return true
      },
      // 設置正確選項
      setCorrect (index, optionIndex) {
        const card = this.formData.cards[index]
        card.correct = optionIndex
        this.$set(this.formData.cards, index, card)
      },
      async generate () {
        const valid = this.validateForm()
        if (!valid) return
        wx.showLoading({
          title: '處理中...',
          mask: true
        })
        const res = await wx.cloud.callFunction({
          name: 'questionAdd',
          data: this.formData
        })
        if (res.result.success) {
          wx.showToast({
            title: '建立成功',
            icon: 'success'
          })
          // 跳轉到投票詳情頁
          setTimeout(() => {
            wx.redirectTo({
              url: `detail-entry?_id=${res.result._id}`
            })
          }, 1500)
        }
      }
    }
  })
</script>


// 省略樣式

成績單

核心要點:小程序canvas製做頁面分享圖
<template>
  <view class="main" wx:if="{{ detail }}">
    <view class="card">
      <view class="title">「 {{ detail.question.title }} 」</view>
      <view class="zql">正確率</view>
      <view class="score">{{ detail.score }}</view>
      <view class="from">
        <image src="{{ detail.creator.avatarUrl }}"></image> {{ detail.creator.nickName }} 的成績單
      </view>
      <view class="result" wx:if="{{ showResult }}">
        <view
          class="item"
          wx:for="{{ detail.result }}"
          wx:key="index"
          wx:style="{{ { background: item.right ? '#4faf70' : '#d94948' } }}"
        >
          {{ item.letter }}
        </view>
      </view>
      <view class="me-too" wx:else bindtap="toCreate">
        我也來出一題
      </view>
      <view class="info">
        <view class="date">
          {{ detail.createTime }}
        </view>
        <view class="date">
          出題人: {{ detail.questionCreator.nickName }}
        </view>
        <view class="num" wx:if="{{ detail.question.answers }}">
          {{ detail.question.answers.length }}次參與
        </view>
      </view>
    </view>
    <view class="action">
      <view class="share" bindtap="generateShareImage">生成分享圖</view>
      <view class="detail" bindtap="toCards" wx:if="{{ user.OPENID === detail.creator.OPENID }}">再試一次</view>
      <view class="detail" bindtap="toDetail" wx:else>我試一下</view>
    </view>
    <!-- 用來生成分享圖 -->
    <canvas
      type="2d"
      id="canvas_share"
      class="canvas-share"
      style="width: {{canvasShare.width}}px; height: {{canvasShare.height}}px"
    />
    <pop visible="{{ imageShare.visible }}" bindclose="closeImageShare">
      <image src="{{ imageShare.image }}" mode="aspectFit" class="image-share"></image>
    </pop>
  </view>
</template>

<script>
  import { createPage } from '@mpxjs/core'
  import no2letter from '../utils/no2letter'
  import loadImage from '../utils/loadImage'
  createPage({
    data: {
      user: null,
      detail: null,
      canvasShare: {
        width: 0,
        height: 0
      },
      imageShare: {
        visible: false,
        image: ''
      },
      showResult: false
    },
    onLoad (params) {
      const id = params._id || params.scene
      this.user = wx.getStorageSync('user')
      this.getDetail(id)
    },
    onShareAppMessage () {
      const title = `我在${this.detail.questionCreator.nickName}的題目中得分${this.detail.score},你也來試試?`
      return {
        title
      }
    },
    methods: {
      closeImageShare () {
        this.imageShare.visible = false
      },
      // 生成分享圖
      async generateShareImage () {
        if (this.imageShare.image) {
          this.imageShare.visible = true
          wx.saveImageToPhotosAlbum({
            filePath: this.imageShare.image,
            success () {
              wx.showToast({
                title: '圖片已經保存到相冊',
                icon: 'none'
              })
            },
            fail () {
              wx.showToast({
                title: '請先在設置裏打開相冊權限',
                icon: 'none'
              })
            }
          })
          return
        }
        wx.showLoading({
          title: '處理中...'
        })
        const res = await wx.cloud.callFunction({
          name: 'wxacode',
          data: {
            page: 'pages/result',
            scene: this.detail._id
          }
        })
        let pageCode
        if (res.result.errCode === 0) {
          pageCode = `data:image/png;base64,${wx.arrayBufferToBase64(res.result.buffer)}`
        } else {
          return
        }
        const query = this.createSelectorQuery()
        query
          .select('#canvas_share')
          .fields({ node: true, size: true })
          .exec(async res => {
            console.log('ressss', res)
            // 獲取 canvas 實例
            const canvas = res[0].node
            // 獲取 canvas 繪圖上下文
            const ctx = canvas.getContext('2d')
            const width = 700
            const height = 900
            this.canvasShare.width = 700
            this.canvasShare.height = 900
            canvas.width = width
            canvas.height = height
            // 繪製背景
            ctx.fillStyle = 'white'
            ctx.fillRect(0, 0, width, height)
            // 繪製head區域
            ctx.textBaseline = 'top'
            ctx.font = '32px sans-serif'
            ctx.fillStyle = '#000000'
            ctx.fillText('小題卡', 20, 20)
            ctx.fillStyle = '#999999'
            ctx.fillText('成績單', 585, 20)
            // 繪製title
            const title = `「${this.detail.question.title}」`
            ctx.font = 'normal bold 50px sans-serif'
            ctx.fillStyle = '#000000'
            ctx.fillText(title, (width - title.length * 50) / 2 + 25, 150)
            // 繪製sub-title
            const subtitle = '我在      的題目中正確率爲'
            ctx.font = '24px sans-serif'
            ctx.fillStyle = '#999'
            ctx.fillText(subtitle, (width - subtitle.length * 24) / 2 + 48, 250)
            // 繪製出題者頭像
            const photoCreator = await loadImage.call(this, this.detail.questionCreator.avatarUrl, 'canvas_share')
            ctx.drawImage(photoCreator, 263, 250, 24, 24)
            // 繪製score
            ctx.font = 'normal bold 200px sans-serif'
            ctx.fillStyle = '#70B7FC'
            ctx.fillText(this.detail.score, (width - this.detail.score.length * 100) / 2 - 80, 350)
            // 繪製welcome
            const welcome = '你也來試試吧'
            ctx.font = '24px sans-serif'
            ctx.fillStyle = '#999'
            ctx.fillText(welcome, (width - welcome.length * 24) / 2, 620)
            // 繪製建立人頭像
            const photoAnswer = await loadImage.call(this, this.detail.creator.avatarUrl, 'canvas_share')
            ctx.drawImage(photoAnswer, 40, 780, 24, 24)
            // 繪製foot-title
            const footTitle = '邀請你一塊兒來答題'
            ctx.font = '24px sans-serif'
            ctx.fillStyle = '#999'
            ctx.fillText(footTitle, 70, 780)
            // 繪製foot-title
            const footSubTitle = '長按圖片識別進入小程序'
            ctx.font = '24px sans-serif'
            ctx.fillStyle = '#999'
            ctx.fillText(footSubTitle, 40, 820)
            // 繪製小程序碼
            const photoPage = await loadImage.call(this, pageCode, 'canvas_share')
            ctx.drawImage(photoPage, 510, 730, 150, 150)
            // 繪製邊框和分割線
            ctx.strokeStyle = '#eee'
            ctx.lineWidth = 8
            ctx.strokeRect(0, 0, width, height)
            ctx.lineWidth = 3
            ctx.beginPath()
            ctx.moveTo(0, 700)
            ctx.lineTo(700, 700)
            ctx.stroke()
            ctx.save()
            wx.hideLoading()
            // 生成圖片預覽
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width,
              height,
              canvas,
              complete: resTemp => {
                console.log('resTemp', canvas, resTemp)
                if (resTemp.errMsg === 'canvasToTempFilePath:ok') {
                  this.imageShare.image = resTemp.tempFilePath
                  this.imageShare.visible = true
                  wx.saveImageToPhotosAlbum({
                    filePath: resTemp.tempFilePath,
                    success () {
                      wx.showToast({
                        title: '圖片已經保存到相冊',
                        icon: 'none'
                      })
                    },
                    fail () {
                      wx.showToast({
                        title: '請先在設置裏打開相冊權限',
                        icon: 'none'
                      })
                    }
                  })
                }
              }
            })
          })
      },
      async getDetail (_id) {
        wx.showLoading({
          title: '加載中...'
        })
        const res = await wx.cloud.callFunction({
          name: 'answerDetail',
          data: {
            _id
          }
        })
        this.detail = res.result.data
        this.detail.result = this.detail.result.map((e, index) => {
          return {
            letter: no2letter(this.detail.answer[index]),
            right: e
          }
        })
        const OPENID = this.user.OPENID
        this.showResult = OPENID === this.detail.creator.OPENID || OPENID === this.detail.questionCreator.OPENID
        wx.hideLoading()
      },
      toCards () {
        wx.navigateTo({
          url: `detail-cards?_id=${this.detail.question._id}`
        })
      },
      toCreate () {
        wx.navigateTo({
          url: 'new'
        })
      },
      toDetail () {
        wx.navigateTo({
          url: `detail-entry?_id=${this.detail.question._id}`
        })
      }
    }
  })
</script>

// 樣式省略

謝謝閱讀

喜歡個人項目,歡迎star支持一下
相關文章
相關標籤/搜索