win10记事本转为html,如何将墨迹笔划转换为文本 (HTML)

如何将墨迹笔划转换为文本 (HTML)

12/11/2015

本文内容

[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]

了解如何在使用 JavaScript 的 Windows 应用商店应用中使用手写识别和将墨迹笔划转换为文本。

针对 Windows 8.1 进行的更新: Windows 8.1 针对指针输入 API 引入了多个更新和改善措施。请参阅 Windows 8.1 的 API 更改获取详细信息。

对于此示例,我们使用 InkManager 对象的内置识别功能 (RecognizeAsync) 将所有墨迹笔划转换为文本并将结果存储在管理器中。

你需要了解的内容

技术

先决条件

本操作方法构建于快速入门:捕获墨迹数据之上。

我们假设你可以创建使用 Windows JavaScript 库模板的使用 JavaScript 的基本 Windows 应用商店应用。

有关使用 WinJS 对象和控件的信息,请参阅快速入门:添加 WinJS 控件和样式。

说明

步骤 1: 创建墨迹管理器

初始化 InkManager 对象,此对象将处理并操作从指针输入获取的墨迹相关数据。

// Create an ink manager.

// InkManager is documented at http://go.microsoft.com/fwlink/?LinkID=260648.

var inkManager = new Windows.UI.Input.Inking.InkManager();

步骤 2: 设置默认识别语言

设置默认识别器语言。对于 Windows 8,每个语言包都包含一组相关的识别语言。有关有效识别语言的详细信息,请参阅 Name。

如果你未设置默认语言,则系统将根据在“语言”控制面板中标识的主要语言来选择一个。如果主要语言不包括识别语言,则系统将使用辅助语言之一或 EN-US。

注意

下面是如何将默认语言设置为 Microsoft English (US) Handwriting Recognizer。

// Set default recognition language.

if (!setRecognizerByName("Microsoft English (US) Handwriting Recognizer")) {

statusMessage.innerText += "\nRecognition: Failed to find English (US) recognizer.";

}

else {

statusMessage.innerText += "\nRecognition: English (US) recognizer.";

}

使用 GetRecognizers 来检索在用户系统上可用的识别语言。迭代此列表,如果找到所需语言,则调用 SetDefaultRecognizer。如果找不到所需语言,则显示一个错误并使用系统默认值。

///

/// Finds a specific recognizer, and sets the inkManager's default to that recognizer.

/// Returns true if successful.

///

/// The name of the handwriting recognizer.

function setRecognizerByName(recognizerName) {

try {

// recognizers is a normal JavaScript array

var recognizers = inkManager.getRecognizers();

for (var i = 0, len = recognizers.length; i < len; i++) {

if (recognizerName === recognizers[i].name) {

inkManager.setDefaultRecognizer(recognizers[i]);

return true;

}

}

}

catch (e) {

displayError("setRecognizerByName: " + e.toString());

}

return false;

}

步骤 3: 启用识别

为用户提供一种启动识别的方式。

首先,声明一组模式按钮。

Ink sample

Load

Save

Draw

Select

Select all

Erase

Erase all

Handwriting recognition

然后,声明一个事件侦听器。

get("recognize").addEventListener("click", recognizeStrokes, false);

步骤 4: 处理所有笔划

最后,通过识别引擎来处理识别请求并处理墨迹管理器管理的所有笔划。

为简单起见,以下示例通过将 InkRecognitionTarget 指定为 all 处理所有笔划。指定 recent 的 InkRecognitionTarget,将仅处理自从上次调用 RecognizeAsync 后添加的笔划。它在以下情况下通常会非常有用:所有笔划都被视为手写,并且它们需要根据诸如 pointerup 等事件而不是用户命令进行动态识别。使用 selected 可仅处理选定笔划。

///

/// Invoked when the "Handwriting recognition" button is pressed.

/// The ink manager processes all strokes through recognizeAsync, which returns

/// the number of words detected and a set of recognition results for each word.

///

/// The event object.

function recognizeStrokes(evt) {

// Ensure ink strokes exist before calling recognizeAsync.

if (inkManager.getStrokes().length > 0) {

// recognizeAsync fails if other recognition tasks are in progress.

try {

// The ink manager is used to store the recognition results.

// recognizeAsync has 3 modes: all | selected | recent.

// For this example, we process all strokes.

// recognizeAsync is documented at http://go.microsoft.com/fwlink/?LinkID=265172.

inkManager.recognizeAsync(Windows.UI.Input.Inking.InkRecognitionTarget.all).done

(

// The recognitionResult object returned by recognizeAsync exposes the

// bounding rect, strokes, and text candidates for each word.

// In this example, we simply display the word count and recognition results.

function (results) {

// recognizeAsync does not automatically update existing recognition results in the ink manager.

// updateRecognitionResults is documented at http://go.microsoft.com/fwlink/?LinkID=265175.

inkManager.updateRecognitionResults(results);

var x = inkManager.getRecognizers();

// Display the number of words returned in results.

statusMessage.innerText = "Words recognized: " + results.length.toString();

// Iterate through each word and display the ranked list of possible matches.

for (var i = 0; i < results.length; i++) {

statusMessage.innerText += "\nWord" + (i+1).toString() + ":";

var alts = results[i].getTextCandidates();

for (var j = 0; j < alts.length; j++) {

statusMessage.innerText += " " + alts[j].toString();

}

}

},

function (e) {

displayError("InkManager::recognizeAsync: " + e.toString());

}

);

}

catch (e) {

displayError("recognize: " + e.toString());

}

}

else {

statusMessage.innerText = "No strokes to recognize.";

}

}

有关如何使用边框和通过 RecognizeAsync 返回的 InkRecognitionResult 对象集合暴露的每个字词的文本候选项的示例,请参阅输入:墨迹示例。 在完成识别后,点击字词将在该字词旁边的弹出窗口中显示一个可选文本候选项列表。

完整示例

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF

ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO

THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A

PARTICULAR PURPOSE.

Copyright (c) Microsoft Corporation. All rights reserved

// Windows Store app that demonstrates the use of the Windows.UI.Input.Inking APIs.

// Ink functionality is documented at http://go.microsoft.com/fwlink/?LinkID=260649.

// User interaction functionality is documented at http://go.microsoft.com/fwlink/?LinkID=260650.

// Ink APIs are documented at http://go.microsoft.com/fwlink/?LinkID=260652.

// Pointer APIs are documented at http://go.microsoft.com/fwlink/?LinkID=260653.

(function ()

{

"use strict";

//

// Global variables

//

// UI object references.

var inkCanvas;

var inkContext;

var modeMessage;

var deviceMessage

var statusMessage;

// Create an ink manager.

// InkManager is documented at http://go.microsoft.com/fwlink/?LinkID=260648.

var inkManager = new Windows.UI.Input.Inking.InkManager();

// Initial pointer values.

var pointerId = -1;

var pointerDeviceType = null;

// Initial stroke property values.

var strokeColor;

var strokeWidth;

//

// End global variables

//

// Obtain reference to the specified element.

function get(elementId)

{

return document.getElementById(elementId);

}

function initialize()

{

// Set up the UI.

inkCanvas = get("inkCanvas");

inkContext = inkCanvas.getContext("2d");

inkContext.lineCap = "round";

inkContext.lineKJoin = "round";

inkCanvas.width = window.innerWidth - 10;

inkCanvas.height = window.innerHeight * 0.5;

deviceMessage = get("deviceMessage");

deviceMessage.innerText = "Undefined";

modeMessage = get("modeMessage");

modeMessage.innerText = inkManager.mode;

statusMessage = get("statusMessage");

statusMessage.innerText = "No pointer input detected."

// Set initial ink mode.

drawStrokes();

// Set default recognition language.

if (!setRecognizerByName("Microsoft English (US) Handwriting Recognizer")) {

statusMessage.innerText += "\nRecognition: Failed to find English (US) recognizer.";

}

else {

statusMessage.innerText += "\nRecognition: English (US) recognizer.";

}

// Set up the handlers for input processing.

inkCanvas.addEventListener("pointerdown", onPointerDown, false);

inkCanvas.addEventListener("pointermove", onPointerMove, false);

inkCanvas.addEventListener("pointerup", onPointerUp, false);

get("save").addEventListener("click", saveStrokes, false);

get("load").addEventListener("click", loadStrokes, false);

get("draw").addEventListener("click", drawStrokes, false);

get("select").addEventListener("click", selectStrokes, false);

get("selectall").addEventListener("click", selectAllStrokes, false);

get("erase").addEventListener("click", eraseStrokes, false);

get("eraseAll").addEventListener("click", eraseAllStrokes, false);

get("recognize").addEventListener("click", recognizeStrokes, false);

}

document.addEventListener("DOMContentLoaded", initialize, false);

function getPointerDeviceType(pId)

{

var pointerDeviceType;

var pointerPoint = Windows.UI.Input.PointerPoint.getCurrentPoint(pId);

switch (pointerPoint.pointerDevice.pointerDeviceType)

{

case Windows.Devices.Input.PointerDeviceType.touch:

pointerDeviceType = "Touch";

break;

case Windows.Devices.Input.PointerDeviceType.pen:

pointerDeviceType = "Pen";

break;

case Windows.Devices.Input.PointerDeviceType.mouse:

pointerDeviceType = "Mouse";

break;

default:

pointerDeviceType = "Undefined";

}

deviceMessage.innerText = pointerDeviceType;

return pointerDeviceType;

}

// Occurs when the pointer (touch, pen, mouse) is detected by the canvas.

// Each stroke begins with onPointerDown.

function onPointerDown(evt)

{

// Get the device type for the pointer input.

pointerDeviceType = getPointerDeviceType(evt.pointerId);

// Process pen and mouse (with left button) only. Reserve touch for manipulations.

if ((pointerDeviceType === "Pen") || ((pointerDeviceType === "Mouse") && (evt.button === 0)))

{

statusMessage.innerText = pointerDeviceType + " pointer down: Start stroke. "

// Process one pointer at a time.

if (pointerId === -1)

{

var current = evt.currentPoint;

// Start drawing the stroke.

inkContext.beginPath();

inkContext.lineWidth = strokeWidth;

inkContext.strokeStyle = strokeColor;

inkContext.moveTo(current.position.x, current.position.y);

// Add current pointer to the ink manager (begin stroke).

inkManager.processPointerDown(current);

// The pointer id is used to restrict input processing to the current stroke.

pointerId = evt.pointerId;

}

}

else

{

// Process touch input.

}

}

// Mouse: Occurs when the pointer moves.

// Pen/Touch: Occurs at a steady rate (approx. 100 messages/second) whether the pointer moves or not.

function onPointerMove(evt)

{

// Process pen and mouse (with left button) only. Reserve touch for manipulations.

if ((pointerDeviceType === "Pen") || ((pointerDeviceType === "Mouse") && (evt.button === -1)))

{

statusMessage.innerText = pointerDeviceType + " pointer move: Draw stroke as lines. "

// The pointer Id is used to restrict input processing to the current stroke.

// pointerId is updated in onPointerDown().

if (evt.pointerId === pointerId)

{

var current = evt.currentPoint;

// Draw stroke in real time.

inkContext.lineTo(current.rawPosition.x, current.rawPosition.y);

inkContext.stroke();

// Add current pointer to the ink manager (update stroke).

inkManager.processPointerUpdate(current);

}

}

else

{

// Process touch input.

}

}

// Occurs when the pointer (touch, pen, mouse) is lifted from the canvas.

// Each stroke ends with onPointerUp.

function onPointerUp(evt)

{

// Process pen and mouse (with left button) only. Reserve touch for manipulations.

if ((pointerDeviceType === "Pen") || ((pointerDeviceType === "Mouse") && (evt.button === 0)))

{

statusMessage.innerText = pointerDeviceType + " pointer up: Finish stroke. "

if (evt.pointerId === pointerId) {

// Add current pointer to the ink manager (end stroke).

inkManager.processPointerUp(evt.currentPoint);

// End live drawing.

inkContext.closePath();

// Render strokes using bezier curves.

renderAllStrokes();

// Reset pointer Id.

pointerId = -1;

}

}

else

{

// Process touch input.

}

}

// Render all strokes using bezier curves instead of line segments.

function renderAllStrokes()

{

statusMessage.innerText += "Render strokes as bezier curves."

// Clear the drawing surface of existing strokes.

inkContext.clearRect(0, 0, inkCanvas.width, inkCanvas.height);

// Iterate through each stroke.

inkManager.getStrokes().forEach(

function (stroke)

{

inkContext.beginPath();

if (stroke.selected) {

inkContext.lineWidth = stroke.drawingAttributes.size.width * 2;

inkContext.strokeStyle = "green";

} else {

inkContext.lineWidth = stroke.drawingAttributes.size.width;

inkContext.strokeStyle = "black";

}

// Enumerate through each line segment of the stroke.

var first = true;

stroke.getRenderingSegments().forEach(

function (segment)

{

// Move to the starting screen location of the stroke.

if (first)

{

inkContext.moveTo(segment.position.x, segment.position.y);

first = false;

}

// Calculate the bezier curve for the segment.

else

{

inkContext.bezierCurveTo(segment.bezierControlPoint1.x,

segment.bezierControlPoint1.y,

segment.bezierControlPoint2.x,

segment.bezierControlPoint2.y,

segment.position.x, segment.position.y);

}

}

);

// Draw the stroke.

inkContext.stroke();

inkContext.closePath();

}

);

}

// Set up draw mode.

function drawStrokes() {

inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.inking;

strokeColor = "black";

strokeWidth = 2;

modeMessage.innerText = inkManager.mode;

}

// Set up selection mode.

function selectStrokes() {

inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.selecting;

strokeColor = "red";

strokeWidth = 1;

modeMessage.innerText = inkManager.mode;

}

// Set up erase mode.

function eraseStrokes() {

inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.erasing;

strokeColor = "gold";

strokeWidth = 1;

modeMessage.innerText = inkManager.mode;

}

// Select all strokes handler.

function selectAllStrokes() {

inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.selecting;

strokeColor = "red";

strokeWidth = 1;

modeMessage.innerText = "Select all strokes.";

// Iterate through each stroke.

inkManager.getStrokes().forEach(

function (stroke) {

stroke.selected = 1;

}

);

renderAllStrokes();

}

// Select all strokes handler.

function eraseAllStrokes() {

inkManager.mode = Windows.UI.Input.Inking.InkManipulationMode.inking;

strokeColor = "black";

strokeWidth = 2;

modeMessage.innerText = "Erase all strokes.";

// Iterate through each stroke.

inkManager.getStrokes().forEach(

function (stroke) {

stroke.selected = 1;

}

);

inkManager.deleteSelected();

renderAllStrokes();

}

// Save all strokes owned by inkManager.

function saveStrokes()

{

// Ensure that strokes exist before calling saveAsync.

if (inkManager.getStrokes().size > 0)

{

// Set up the file save screen.

var savePicker = Windows.Storage.Pickers.FileSavePicker();

savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;

savePicker.fileTypeChoices.insert("GIF with embedded ISF", [".gif"]);

savePicker.defaultFileExtension = ".gif";

// Set up the stream.

var saveStream = null;

// Asynchronously save the ink data to the stream.

savePicker.pickSaveFileAsync().done(

function (file)

{

if (null !== file)

{

file.openAsync(Windows.Storage.FileAccessMode.readWrite).then(

function (stream)

{

saveStream = stream;

return inkManager.saveAsync(saveStream);

}

).then(

function ()

{

return saveStream.flushAsync();

},

function (e) {

// Override the standard saveAsync error with our own.

throw new Error("saveAsync");

}

).done(

function ()

{

statusMessage.innerText = "Strokes saved as GIF with embedded ISF (.gif).";

saveStream.close();

},

function (e) {

statusMessage.innerText = "Save: " + e.toString();

// Close the stream if open.

if (saveStream) {

saveStream.close();

}

}

);

}

}

);

}

else

{

statusMessage.innerText = "No strokes to save.";

}

}

// Load strokes into an inkManager.

function loadStrokes()

{

// Set up the file open screen.

var openPicker = Windows.Storage.Pickers.FileOpenPicker();

openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;

openPicker.fileTypeFilter.replaceAll([".gif"]);

// Set up the stream.

var loadStream = null;

// Asynchronously load the ink data from the stream.

openPicker.pickSingleFileAsync().done(

function (file)

{

if (null != file)

{

file.openAsync(Windows.Storage.FileAccessMode.read).then(

function (stream) {

loadStream = stream;

return inkManager.loadAsync(loadStream);

}).done(

function()

{

var strokes = inkManager.getStrokes().length;

if (strokes === 0)

{

statusMessage.innerText = "No strokes in file.";

}

else

{

statusMessage.innerText = strokes + " strokes loaded.";

}

renderAllStrokes();

loadStream.close();

},

function (e)

{

statusMessage.innerText = "Load failed.";

if (loadStream)

{

// Close the stream if open.

loadStream.close();

}

});

}

});

}

///

/// Finds a specific recognizer, and sets the inkManager's default to that recognizer.

/// Returns true if successful.

///

/// The name of the handwriting recognizer.

function setRecognizerByName(recognizerName) {

try {

// recognizers is a normal JavaScript array

var recognizers = inkManager.getRecognizers();

for (var i = 0, len = recognizers.length; i < len; i++) {

if (recognizerName === recognizers[i].name) {

inkManager.setDefaultRecognizer(recognizers[i]);

return true;

}

}

}

catch (e) {

displayError("setRecognizerByName: " + e.toString());

}

return false;

}

///

/// Invoked when the "Handwriting recognition" button is pressed.

/// The ink manager processes all strokes through recognizeAsync, which returns

/// the number of words detected and a set of recognition results for each word.

///

/// The event object.

function recognizeStrokes(evt) {

// Ensure ink strokes exist before calling recognizeAsync.

if (inkManager.getStrokes().length > 0) {

// recognizeAsync fails if other recognition tasks are in progress.

try {

// The ink manager is used to store the recognition results.

// recognizeAsync has 3 modes: all | selected | recent.

// For this example, we process all strokes.

// recognizeAsync is documented at http://go.microsoft.com/fwlink/?LinkID=265172.

inkManager.recognizeAsync(Windows.UI.Input.Inking.InkRecognitionTarget.all).done

(

// The recognitionResult object returned by recognizeAsync exposes the

// bounding rect, strokes, and text candidates for each word.

// In this example, we simply display the word count and recognition results.

function (results) {

// recognizeAsync does not automatically update existing recognition results in the ink manager.

// updateRecognitionResults is documented at http://go.microsoft.com/fwlink/?LinkID=265175.

inkManager.updateRecognitionResults(results);

var x = inkManager.getRecognizers();

// Display the number of words returned in results.

statusMessage.innerText = "Words recognized: " + results.length.toString();

// Iterate through each word and display the ranked list of possible matches.

for (var i = 0; i < results.length; i++) {

statusMessage.innerText += "\nWord" + (i+1).toString() + ":";

var alts = results[i].getTextCandidates();

for (var j = 0; j < alts.length; j++) {

statusMessage.innerText += " " + alts[j].toString();

}

}

},

function (e) {

displayError("InkManager::recognizeAsync: " + e.toString());

}

);

}

catch (e) {

displayError("recognize: " + e.toString());

}

}

else {

statusMessage.innerText = "No strokes to recognize.";

}

}

// Returns true if any strokes inside the ink manager are selected; false otherwise.

function anySelected() {

var strokes = inkManager.getStrokes();

var len = strokes.length;

for (var i = 0; i < len; i++) {

if (strokes[i].selected) {

return true;

}

}

return false;

}

})();

相关主题

概念

参考

示例 (DOM)

示例(Windows 应用商店应用  API)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值