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

Discuss the development trend of Baidu Encyclopedia UI

<br />The official version of Baidu Encyclop...

Write a formal blog using XHTML CSS

The full name of Blog should be Web log, which mea...

How to position the header at the top using CSS sticky layout

Application scenarios: One of the new requirement...

Install Percona Server+MySQL on CentOS 7

1. Environmental Description (1) CentOS-7-x86_64,...

The whole process record of vue3 recursive component encapsulation

Table of contents Preface 1. Recursive components...

How to write beautiful HTML code

What Beautiful HTML Code Looks Like How to write ...

Implementation of tomcat image created with dockerfile based on alpine

1. Download the alpine image [root@docker43 ~]# d...

CSS menu button animation

To write a drop-down menu, click the button. The ...

Solution to slow response of Tomcat server

1. Analytical thinking 1. Eliminate the machine&#...

JavaScript plugin encapsulation for table switching

This article shares the encapsulation code of Jav...

Implementation of IP address configuration in Centos7.5

1. Before configuring the IP address, first use i...

Specific use of MySQL window functions

Table of contents 1. What is a window function? 1...

Web page comments cause text overflow in IE

The experimental code is as follows: </head>...

What is this in JavaScript point by point series

Understand this Perhaps you have seen this in oth...