Giter Club home page Giter Club logo

vue-fortune-wheel's Introduction

Vue-Fortune-Wheel For Vue3

Component name: Wheel of Fortune, Wheel of Fortune, Wheel of Fortune

Application scenario: lottery

For Vue2

Viewing Documents

Install

yarn add vue-fortune-wheel

or

npm install vue-fortune-wheel

Language

English (By Google Translate)| δΈ­ζ–‡

Demo

online

https://xiaolin1995.github.io/vue-fortune-wheel/demo/

Usage

<template>
  <div>
    <!-- type: image -->
    <FortuneWheel
      style="width: 500px; max-width: 100%;"
      ref="wheelEl"
      type="image"
      :useWeight="true"
      :verify="canvasVerify"
      :prizeId="prizeId"
      :angleBase="-2"
      :prizes="prizesImage"
      @rotateStart="onImageRotateStart"
      @rotateEnd="onRotateEnd"
    >
      <template #wheel>
        <img src="./assets/wheel.png" style="width: 100%;transform: rotateZ(60deg)" />
      </template>
      <template #button>
        <img src="./assets/button.png" style="width: 180px"/>
      </template>
    </FortuneWheel>


    <!-- type: canvas -->
    <FortuneWheel
      style="width: 500px; max-width: 100%;"
      :verify="canvasVerify"
      :canvas="canvasOptions"
      :prizes="prizesCanvas"
      @rotateStart="onCanvasRotateStart"
      @rotateEnd="onRotateEnd"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import FortuneWheel from 'vue-fortune-wheel'
import 'vue-fortune-wheel/style.css'

const prizeId = ref(0)

const wheelEl = ref()
const canvasVerify = ref(false) // Whether the turntable in canvas mode is enabled for verification
const verifyDuration = 2
const canvasOptions = {
  btnWidth: 140,
  borderColor: '#584b43',
  borderWidth: 6,
  lineHeight: 30
}

const prizesCanvas = [
  {
    id: 1, //* The unique id of each prize, an integer greater than 0
    name: 'Blue', // Prize name, display value when type is canvas (this parameter is not needed when type is image)
    value: 'Blue\'s value', //* Prize value, return value after spinning
    bgColor: '#45ace9', // Background color (no need for this parameter when type is image)
    color: '#ffffff', // Font color (this parameter is not required when type is image)
    probability: 30 //* Probability, up to 4 decimal places (the sum of the probabilities of all prizes
  },
  {
    id: 2,
    name: 'Red',
    value: 'Red\'s value',
    bgColor: '#dd3832',
    color: '#ffffff',
    probability: 40
  },
  {
    id: 3,
    name: 'Yellow',
    value: 'Yellow\'s value',
    bgColor: '#fef151',
    color: '#ffffff',
    probability: 30
  }
]

const prizesImage = [
  {
    id: 1, //* The unique id of each prize, an integer greater than 0
    value: 'Blue\'s value', //* Prize value, return value after spinning
    weight: 1 // Weight, if useWeight is true, the probability is calculated by weight (weight must be an integer), so probability is invalid
  },
  {
    id: 2,
    value: 'Red\'s value',
    weight: 0
  },
  {
    id: 3,
    value: 'Yellow\'s value',
    weight: 0
  }
]

const prizeRes = computed(() => {
  return prizesCanvas.find(item => item.id === prizeId.value) || prizesCanvas[0]
})


onMounted(() => {
  wheelEl.value.startRotate() // Can start rotation
})

// Simulate the request back-end interface
function testRequest (verified, duration) { // verified: whether to pass the verification, duration: delay time
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(verified)
    }, duration)
  })
}

function onCanvasRotateStart (rotate) {
  if (canvasVerify.value) {
    const verified = true // true: the test passed the verification, false: the test failed the verification
    testRequest(verified, verifyDuration * 1000).then((verifiedRes) => {
      if (verifiedRes) {
        console.log('Verification passed, start to rotate')
        rotate() // Call the callback, start spinning
        canvasVerify.value = false // Turn off verification mode
      } else {
        alert('Failed verification')
      }
    })
    return
  }
  console.log('onCanvasRotateStart')
}

function onImageRotateStart () {
  console.log('onImageRotateStart')
}

function onRotateEnd (prize) {
  alert(prize.value)
}

function onChangePrize (id) {
  prizeId.value = id
}
</script>

FortuneWheel Events

Event name Description Callback parameters
rotateStart Triggered when the dial button is clicked When verify is true, there will be a callback, and the callback function will be called to start spinning
rotateEnd Triggered at the end of the turntable animation The entire prize Object

FortuneWheel Methods

Event name Description Callback parameters
startRotate Can trigger rotation When verify is true, the callback function is triggered in the rotateStart event

FortuneWheel Attributes

Parameters Description Type Default Value
type Type of turntable (canvas, image) String canvas
useWeight Whether to calculate probability by weight Boolean false
disabled Whether to disable (after disabled, click the button will not rotate) Boolean false
verify Whether to enable verification mode Boolean false
canvas.radius Radius of circle (type: canvas) Number 250
canvas.textRadius The distance of the text from the center of the circle (type: canvas) Number 190
canvas.textLength A few characters in one line of the prize, beyond the line break (maximum two lines) Number 6
canvas.textDirection Prize text direction (horizontal, vertical) String horizontal
canvas.lineHeight Text line height (type: canvas) Number 20
canvas.borderWidth Round outer border (type: canvas) Number 0
canvas.borderColor Color value of the outer border (type: canvas) String transparent
canvas.btnText Button text (type: canvas) String GO
canvas.btnWidth Button width (px) Number 140
canvas.fontSize Prize size (px) Number 34
duration Time to complete one rotation (unit: ms) Number 6000
timingFun Css time function of rotation transition String cubic-bezier(0.36, 0.95, 0.64, 1)
angleBase Number of rotations (angleBase * 360 is the total angle of one rotation, it can be reversed when it is a negative number) Number 10
prizeId Specify the id, it will spin to the prize of this id every time (when it is 0, the value can be changed during the rotation according to the probability of each prize itself to complete various show operations) Number 0
prizes Prize list (structure reference Usage) Array /

vue-fortune-wheel's People

Contributors

xiaolin1995 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vue-fortune-wheel's Issues

API method to start rotation?

Hi, I was wondering if there's an available method to start the rotation programmatically, instead of pressing the rotate button.

Thanks!

I want to spin without click button spin

index.js?!./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./components/WheelOfFortune.vue?vue&type=script&lang=js:96 Uncaught TypeError: fortuneWheel.rotate is not a function
at eval (index.js?!./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./components/WheelOfFortune.vue?vue&type=script&lang=js:96:24)

Mobile not working

Hey XiaoLin,

I really love your fortune wheel. Great work.
Unfortunately I have some trouble getting this work on mobile devices. Desktop works fine but my smartphone is not able to trigger the rotate-function.

This is my code when i trigger @rotateStart:

...
onCanvasRotateStart(rotate) {
if (this.allowedToPlay === true) {
rotate();
}
},
...

Any ideas about whats the issue?

Thanks a lot,
Flo

Ask: How to trigger rotation programaticaly

Hi, first of all, thanks for making this awesome component.

I want to ask, is there any function to start rotation?
I tried this and got :
caught TypeError: this.$refs.fortuneWheel.onRotateStart is not a function

my application use websocket to set prizeId and I need that function to trigger rotation, is it posible?

I use:
[email protected]
[email protected]

sorry for my bad english :)
Thank you!

[Vue 3] Component migrated

<template>
  <div class="fw-container">
    <!-- wheel -->
    <div
      class="fw-wheel"
      :style="rotateStyle"
      @transitionend="onRotateEnd"
      @webkitTransitionend="onRotateEnd"
    >
      <canvas
        v-if="type === 'canvas'"
        ref="wheel"
        :width="canvasConfig.radius * 2"
        :height="canvasConfig.radius * 2"
      ></canvas>
      <slot name="wheel" v-else></slot>
    </div>
    <!-- button -->
    <div class="fw-btn">
      <div
        v-if="type === 'canvas'"
        class="fw-btn__btn"
        :style="{ width: canvasConfig.btnWidth + 'px', height: canvasConfig.btnWidth + 'px' }"
        @click="handleClick"
      >
        {{ canvasConfig.btnText }}
      </div>
      <div v-else class="fw-btn__image" @click="handleClick">
        <slot name="button"></slot>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, toRef } from 'vue'
import sumBy from 'lodash/sumBy'
import random from 'lodash/random'

const canvasDefaultConfig = {
  radius: 250,
  textRadius: 190,
  textLength: 6,
  textDirection: 'horizontal',
  lineHeight: 20,
  borderWidth: 0,
  borderColor: 'transparent',
  btnText: 'GO',
  btnWidth: 140,
  fontSize: 34
}

const props = defineProps({
  type: {
    type: String,
    default: 'canvas' // canvas || image
  },
  useWeight: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  verify: {
    type: Boolean,
    default: false
  },
  canvas: {
    type: Object,
    default: () => ({
      radius: 250,
      textRadius: 190,
      textLength: 6,
      textDirection: 'horizontal',
      lineHeight: 20,
      borderWidth: 0,
      borderColor: 'transparent',
      btnText: 'GO',
      btnWidth: 140,
      fontSize: 34
    })
  },
  duration: {
    type: Number,
    default: 6000
  },
  timingFun: {
    type: String,
    default: 'cubic-bezier(0.36, 0.95, 0.64, 1)'
  },
  angleBase: {
    type: Number,
    default: 10
  },
  prizeId: {
    type: Number,
    default: 0
  },
  prizes: {
    type: Array,
    required: true,
    default: () => []
  }
})
const emits = defineEmits(['rotateStart', 'rotateEnd'])
const prizeId = toRef(props, 'prizeId')

const wheel = ref(null)
const isRotating = ref(false)
const rotateEndDeg = ref(false)
const prizeRes = ref({})

const canvasConfig = computed(() => Object.assign(canvasDefaultConfig, props.canvas))
const probabilityTotal = computed(() => {
  if (props.useWeight) return 100
  return sumBy(props.prizes, (row) => row.probability || 0)
})
const prizesIdArr = computed(() => {
  const idArr = []
  props.prizes.forEach((row) => {
    const count = props.useWeight ? row.weight || 0 : (row.probability || 0) * decimalSpaces.value
    const arr = new Array(count).fill(row.id)
    idArr.push(...arr)
  })
  return idArr
})
const decimalSpaces = computed(() => {
  if (props.useWeight) return 0
  const sortArr = [...props.prizes].sort((a, b) => {
    const aRes = String(a.probability).split('.')[1]
    const bRes = String(b.probability).split('.')[1]
    const aLen = aRes ? aRes.length : 0
    const bLen = bRes ? bRes.length : 0
    return bLen - aLen
  })
  const maxRes = String(sortArr[0].probability).split('.')[1]
  const idx = maxRes ? maxRes.length : 0
  return [1, 10, 100, 1000, 10000][idx > 4 ? 4 : idx]
})
const rotateStyle = computed(() => ({
  '-webkit-transform': `rotateZ(${rotateEndDeg.value}deg)`,
  transform: `rotateZ(${rotateEndDeg.value}deg)`,
  '-webkit-transition-duration': `${rotateDuration.value}s`,
  'transition-duration': `${rotateDuration.value}s`,
  '-webkit-transition-timing-function:': props.timingFun,
  'transition-timing-function': props.timingFun
}))

const rotateDuration = computed(() => (isRotating.value ? props.duration / 1000 : 0))
const rotateBase = computed(() => {
  let angle = props.angleBase * 360
  if (props.angleBase < 0) angle -= 360
  return angle
})
const canRotate = computed(
  () => !props.disabled && !isRotating.value && probabilityTotal.value === 100
)

function getStrArray(str, len) {
  const arr = []
  while (str !== '') {
    let text = str.substr(0, len)
    if (str.charAt(len) !== '' && str.charAt(len) !== ' ') {
      const index = text.lastIndexOf(' ')
      if (index !== -1) text = text.substr(0, index)
    }
    str = str.replace(text, '').trim()
    arr.push(text)
  }
  return arr
}

function getTargetDeg(prizeId) {
  const angle = 360 / props.prizes.length
  const num = props.prizes.findIndex((row) => row.id === prizeId)
  prizeRes.value = props.prizes[num]
  return 360 - (angle * num + angle / 2)
}

function checkProbability() {
  if (probabilityTotal.value !== 100) {
    throw new Error('Prizes Is Error: Sum of probabilities is not 100!')
  }
  return true
}

function drawPrizeText(ctx, angle, arc, name) {
  const { lineHeight, textLength, textDirection } = canvasConfig.value
  const content = getStrArray(name, textLength)
  if (content === null) return
  textDirection === 'vertical'
    ? ctx.rotate(angle + arc / 2 + Math.PI)
    : ctx.rotate(angle + arc / 2 + Math.PI / 2)
  content.forEach((text, idx) => {
    let textX = -ctx.measureText(text).width / 2
    let textY = (idx + 1) * lineHeight
    if (textDirection === 'vertical') {
      textX = 0
      textY = (idx + 1) * lineHeight - (content.length * lineHeight) / 2
    }
    ctx.fillText(text, textX, textY)
  })
}

function drawCanvas() {
  const canvasEl = wheel.value
  if (canvasEl.getContext) {
    const { radius, textRadius, borderWidth, borderColor, fontSize } = canvasConfig.value
    const arc = Math.PI / (props.prizes.length / 2)
    const ctx = canvasEl.getContext('2d')
    ctx.clearRect(0, 0, radius * 2, radius * 2)
    ctx.strokeStyle = borderColor
    ctx.lineWidth = borderWidth * 2
    ctx.font = `${fontSize}px Arial`
    props.prizes.forEach((row, i) => {
      const angle = i * arc - Math.PI / 2
      ctx.fillStyle = row.bgColor
      ctx.beginPath()
      ctx.arc(radius, radius, radius - borderWidth, angle, angle + arc, false)
      ctx.stroke()
      ctx.arc(radius, radius, 0, angle + arc, angle, true)
      ctx.fill()
      ctx.save()
      ctx.fillStyle = row.color
      ctx.translate(
        radius + Math.cos(angle + arc / 2) * textRadius,
        radius + Math.sin(angle + arc / 2) * textRadius
      )
      drawPrizeText(ctx, angle, arc, row.name)
      ctx.restore()
    })
  }
}

function handleClick() {
  if (!canRotate.value) return
  if (props.verify) {
    emits('rotateStart', onRotateStart)
    return
  }
  emits('rotateStart')
  onRotateStart()
}

function onRotateStart() {
  isRotating.value = true
  const prizeId = props.prizeId || getRandomPrize()
  rotateEndDeg.value = rotateBase.value + getTargetDeg(prizeId)
}

function onRotateEnd() {
  isRotating.value = false
  rotateEndDeg.value %= 360
  emits('rotateEnd', prizeRes.value)
}

function getRandomPrize() {
  const len = prizesIdArr.value.length
  const prizeId = prizesIdArr.value[random(0, len - 1)]
  return prizeId
}

onMounted(() => {
  checkProbability()
  if (props.type === 'canvas') drawCanvas()
})

// prizeId
watch(prizeId, (newVal) => {
  if (!isRotating.value) return
  let newAngle = getTargetDeg(newVal)
  if (props.angleBase < 0) newAngle -= 360
  const prevEndDeg = rotateEndDeg.value
  let nowEndDeg = props.angleBase * 360 + newAngle
  const angle = 360 * Math.floor((nowEndDeg - prevEndDeg) / 360)
  if (props.angleBase >= 0) {
    nowEndDeg += Math.abs(angle)
  } else {
    nowEndDeg += -360 - angle
  }
  rotateEndDeg.value = nowEndDeg
})
</script>

<style scoped lang="scss">
@import './style.scss';
</style>

Probabilities sum not matching 100

Hi,

I'm unable to match the "100%" sum requirement if I use decimals, for example, if I have 3 prizes and I want them to have the same probability, I tried 33.3333, 33.3333333, 100/3 ... But nothing worked.

Is there a way to do that? I think, it'll probably be better to have a system based on weight to define the probabilities.

Thanks!

Can't have weight working

Hi there,

Thank you so much for the weight addon, I'm trying to have it working and I'm unable to do it.

I have version "vue-fortune-wheel": "^0.3.4".

My FortuneWheel looks like:

<FortuneWheel
  v-if="showWheel"
  style="width: 100%"
  borderColor="#584b43"
  :borderWidth="1"
  :textLength="3"
  :useWeight="true"
  :fontSize="fontSize"
  :textRadius="230"
  :prizes="prizes"
  @rotateStart="onCanvasRotateStart"
  @rotateEnd="onRotateEnd"
/>

And I have weight property defined in every prize.

When I enter the wheel, I get this warning:
[Vue warn]: Error in created hook: "TypeError: Cannot read property 'toString' of undefined"

And it goes away when I insert probabilities in every prize, then I have it working but it's using probabilities and not weights.

Thanks!

Enhancement: vertical text

Hi,

It would be nice to have an option to have vertical text, it would be helpful for using with long texts or when you have a lot of prizes.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.