我使用Web Speech API来使用JavaScript操作SVG Shapes。我可以设法说出命令并使形状出现在屏幕上,但问题是我不知道如何使用语音命令选择和移动形状。
示例:如何选择形状ID,然后说出向左,向右,向上,向下移动的命令。
以下JavaScript代码:
var counter = 0;
function buildCircle(x, y, colour) {
if (buildCircle) {
getElementById = "counter";
counter++; // Increment the ID by 1 when a new shape is created
}
var f = document.createElementNS("http://www.w3.org/2000/svg", "circle");
f.setAttribute("id", counter);
f.setAttribute("cx", 350);
f.setAttribute("cy", 350);
f.setAttribute("r", "40");
f.setAttribute("fill", colour);
f.setAttribute("fill-opacity", "0.4");
f.setAttribute("stroke", colour);
svgOut.appendChild(f);
}
function buildSquare(x, y, colour) {
var f = document.createElementNS("http://www.w3.org/2000/svg", "rect");
if (buildSquare) {
getElementById = "counter";
counter++;
}
f.setAttribute("id", counter);
f.setAttribute("x", 200);
f.setAttribute("y", 300);
f.setAttribute("width", "80");
f.setAttribute("height", "80");
f.setAttribute("fill", colour);
f.setAttribute("fill-opacity", "0.4");
f.setAttribute("stroke", colour);
svgOut.appendChild(f);
}
function buildLine(x, y, colour, id) {
if (buildLine) {
getElementById = "counter";
counter++;
}
var f = document.createElementNS("http://www.w3.org/2000/svg", "line");
f.setAttribute("id", counter);
f.setAttribute("x1", 160);
f.setAttribute("y1", 400);
f.setAttribute("x2", "160");
f.setAttribute("y2", "300");
f.setAttribute("stroke", colour);
f.setAttribute("stroke-width", 5);
f.setAttribute("fill-opacity", "0.4");
svgOut.appendChild(f);
}
function interpret(text) {
var result = text.match(/(purple|red|green|blue|yellow|orange|black|pink).+(square|circle|line)/i);
if (result) {
switch (result[2].toLowerCase()) {
case "square":
buildSquare(
lastMouseEvent.clientX,
lastMouseEvent.clientY,
result[1]
);
break;
case "circle":
buildCircle(
lastMouseEvent.clientX,
lastMouseEvent.clientY,
result[1]
);
break;
case "line":
buildLine(
lastMouseEvent.clientX,
lastMouseEvent.clientY,
result[1]
);
break;
}
}
}
HTML代码