Vue uses canvas handwriting input to recognize Chinese

Vue uses canvas handwriting input to recognize Chinese

Effect picture:

Preface:

Recently, I was working on an outdoor large-screen project. The input method on the system was not convenient to use, so the customer requested a handwriting input method that could be embedded in a web page.

core:

Backend interface API: Use QQ input method handwriting interface

https://handwriting.shuru.qq.com/cloud/cgi-bin/cloud_hw_pub.wsgi

parameter illustrate type default value
track_str Stroke string. Single strokes are concatenated in the format of 'x1, y1, x2, y2, ...'. Multiple strokes are concatenated in the format of eb based on single strokes, for example 'x1, y1, x2, y2, eb, x3, y3, x4, y4' string -
cmd Unknown, currently 0 number -

Note: This interface was learned from other big guys’ articles. The original text is here. I have not been able to find the relevant address of the official document. If anyone knows it, please leave a message to let me know. Thank you!

Ideas:

(1) Create a canvas drawing area

// template
<div class="canvas-container">
 <canvas ref="canvas" width="300" height="200">Your browser does not support canvas, please upgrade your browser. </canvas>
</div>

//scss
.canvas-container {
 background: #fafafa;

 canvas {
 background: #fff;
  border: 1px solid #000;
 }
}


(2) Obtaining the initial horizontal and vertical coordinates

data() {
  return {
    initX: 0, // initial horizontal coordinate initY: 0, // initial vertical coordinate}
},
mounted() {
  this.initBound()
},
methods: {
  // Initialize canvas position initBound() {
    let bound = this.$refs.canvas.getBoundingClientRect()
    this.initX = bound.x
    this.initY = bound.y
  }
}

(3) Add mouse click events, move events, and release events

// template
<div class="canvas-container">
 <canvas ref="canvas" width="300" height="200" @mousedown="onMouseDown" @mousemove="onMouseMove" @mouseup="onMouseUp">Your browser does not support canvas, please upgrade your browser. </canvas>
</div>
// script
data() {
  return {
    // ...
    
    lastX: 0, // previous horizontal coordinatelastY: 0, // previous vertical coordinateisHandWrite: false, // whether to start handwritingpointsXY: [], // single strokeallPointsXY: [], // all strokes}
},
methods: {
  onMouseDown(e) {
    this.pointsXY = []
    let cx = e.clientX - this.initX
    let cy = e.clientY - this.initY
    this.lastX = cx
    this.lastY = cy
    this.pointsXY.push(cx)
    this.pointsXY.push(cy)
    this.isHandWrite = true
  },
  onMouseMove(e) {
    if (this.isHandWrite) {
      let cx = e.clientX - this.initX
      let cy = e.clientY - this.initY
      this.pointsXY.push(cx - this.lastX)
      this.pointsXY.push(cy - this.lastY)
      // Get the 2d context object let ctx = this.$refs.canvas.getContext('2d')
      // Create a new path ctx.beginPath()
      ctx.strokeStyle = '#000'
      ctx.fillStyle = '#000'
      ctx.lineWidth = 8
      ctx.lineCap = 'round'
      ctx.moveTo(this.lastX, this.lastY)
      ctx.lineTo(cx, cy)
      ctx.stroke()
      this.lastX = cx
      this.lastY = cy
    }
  },
  onMouseUp(e) {
    if (this.isHandWrite) {
      this.isHandWrite = false
      this.allPointsXY.push(this.pointsXY.join(','))
      this.queryText() // Recognize text}
  },
}


(4) Add text recognition interface and jsonp callback function. Vue-jsonp is used for cross-domain requests. For specific usage, please refer to the usage of jsonp in vue.

// script
data() {
  return {
    // ...
    
    write_result: [], // Return similar words}
},
mounted() {
  // ...

  let _this = this
  // Add jsonp callback function, qq input method specific window['QQShuru'] = {
    HWPanel:
      ajax_callback: function (res) {
        _this.write_result = res.cand
      },
    },
  }
},
methods: {
  queryText() {
    let track_str = this.allPointsXY.join(',eb,')
    this.$jsonp(
      `https://handwriting.shuru.qq.com/cloud/cgi-bin/cloud_hw_pub.wsgi?track_str=${track_str}&cmd=0`
    ).catch(err => {
      console.log(err)
    })
  },
}


(5) Finally, add a rewrite button to clear the canvas.

// template
<div>
  <button @click="onReload">Rewrite</button>
</div>

// script
onReload() {
  if (!this.$refs.canvas) return
  this.pointsXY = []
  this.allPointsXY = []
  let ctx = this.$refs.canvas.getContext('2d')
  ctx.clearRect(0, 0, 300, 200)
}

The full code is as follows:

<template>
  <div id="app">
    <div class="canvas-container">
      <canvas ref="canvas" width="300" height="200" @mousedown="onMouseDown" @mousemove="onMouseMove" @mouseup="onMouseUp">Your browser does not support canvas, please upgrade your browser. </canvas>
    </div>
    <div>[{{ lastX + ', ' + lastY }}]</div>
    <div>
      <button @click="onReload">Rewrite</button>
    </div>
    <div>Return similar words: {{ write_result }}</div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      initX: 0, // Initial horizontal coordinateinitY: 0, // Initial vertical coordinatelastX: 0, // Previous horizontal coordinatelastY: 0, // Previous vertical coordinateisHandWrite: false, // Whether to start handwritingpointsXY: [], // Single strokeallPointsXY: [], // All strokeswrite_result: [], // Return similar characters}
  },
  mounted() {
    this.initBound()

    let _this = this
    // Add jsonp callback function, qq input method specific window['QQShuru'] = {
      HWPanel:
        ajax_callback: function (res) {
          _this.write_result = res.cand
        },
      },
    }
  },
  methods: {
    // Initialize canvas position initBound() {
      let bound = this.$refs.canvas.getBoundingClientRect()
      this.initX = bound.x
      this.initY = bound.y
    },
    onMouseDown(e) {
      console.log('onDown', e)
      this.pointsXY = []
      let cx = e.clientX - this.initX
      let cy = e.clientY - this.initY
      this.lastX = cx
      this.lastY = cy
      this.pointsXY.push(cx)
      this.pointsXY.push(cy)
      this.isHandWrite = true
    },
    onMouseMove(e) {
      if (this.isHandWrite) {
        let cx = e.clientX - this.initX
        let cy = e.clientY - this.initY
        this.pointsXY.push(cx - this.lastX)
        this.pointsXY.push(cy - this.lastY)
        // Get the 2d context object let ctx = this.$refs.canvas.getContext('2d')
        // Create a new path ctx.beginPath()
        ctx.strokeStyle = '#000'
        ctx.fillStyle = '#000'
        ctx.lineWidth = 8
        ctx.lineCap = 'round'
        ctx.moveTo(this.lastX, this.lastY)
        ctx.lineTo(cx, cy)
        ctx.stroke()
        this.lastX = cx
        this.lastY = cy
      }
    },
    onMouseUp(e) {
      if (this.isHandWrite) {
        this.isHandWrite = false
        this.allPointsXY.push(this.pointsXY.join(','))
        this.queryText()
      }
    },
    // Recognize text queryText() {
      let track_str = this.allPointsXY.join(',eb,')
      this.$jsonp(
        `https://handwriting.shuru.qq.com/cloud/cgi-bin/cloud_hw_pub.wsgi?track_str=${track_str}&cmd=0`
      ).catch(err => {
        console.log(err)
      })
    },
    onReload() {
      if (!this.$refs.canvas) return
      this.pointsXY = []
      this.allPointsXY = []
      let ctx = this.$refs.canvas.getContext('2d')
      ctx.clearRect(0, 0, 300, 200)
    },
  },
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;

  .canvas-container {
    background: #fafafa;

    canvas {
      background: #fff;
      border: 1px solid #000;
    }
  }
}
</style>

This is the end of this article about vue using canvas handwriting input to recognize Chinese. For more relevant vue using canvas handwriting input to recognize Chinese content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue uses Canvas to generate random sized and non-overlapping circles
  • Vue uses canvas to realize image compression upload
  • How to draw the timeline with vue+canvas
  • VUE+Canvas realizes the whole process of a simple Gobang game
  • VUE+Canvas implements the game of God of Wealth receiving ingots
  • How to use VUE and Canvas to implement a Thunder Fighter typing game
  • VUE+Canvas implements the sample code of the desktop pinball brick-breaking game
  • Vue uses the mouse to draw a rectangle on Canvas
  • Vue uses canvas to implement mobile handwritten signature
  • Vue+canvas realizes puzzle game

<<:  Web page text design should be like smart girls wearing clothes

>>:  How to pass parameters to JS via CSS

Recommend

MySQL big data query optimization experience sharing (recommended)

Serious MySQL optimization! If the amount of MySQ...

Apache Spark 2.0 jobs take a long time to finish when they are finished

Phenomenon When using Apache Spark 2.x, you may e...

Linux method example to view all information of the process

There is a task process on the server. When we us...

MySQL database master-slave configuration tutorial under Windows

The detailed process of configuring the MySQL dat...

Tutorial on installing mysql5.7.36 database in Linux environment

Download address: https://dev.mysql.com/downloads...

Nginx Layer 4 Load Balancing Configuration Guide

1. Introduction to Layer 4 Load Balancing What is...

JS implements dragging the progress bar to change the transparency of elements

What I want to share today is to use native JS to...

Details of 7 kinds of component communication in Vue3

Table of contents 1. Vue3 component communication...

HTML tag ID can be a variable

<table id=" <%=var1%>">, the...

Example of implementing GitHub's third-party authorization method in Vue

Table of contents Creating OAuth Apps Get the cod...

HTML weight loss Streamline HTML tags to create web pages

HTML 4 HTML (not XHTML), MIME type is text/html, ...