简体   繁体   中英

How can I recognize a hand drawn shape is similar to a SVG Model

I would like to let users re-draw over a svg shape (the number 8), and be able to detect if the shape is well completed or not. The user will have to re-draw over the borders of this svg, with his finger on mobile, to be abIe to continue through the website. I want to use Javascript.

My first approach was to use hidden divs and detect whenever the mouse passes over each one in the right order (see sketch ), but there can be errors. And I would also like to highlight the drawn track in a way to show the filling progress.

Which approach should I use ?

Well, it depends on how you implemented your drawing canvas. Without the actual code, it's difficult to provide a good answer.

Regardless, you might try to use a second path that is hidden/transparent and overlaps the first one.

Then capture the mouseenter/mouseleave (or whatever events you're using to "draw") and based on the event coordinates, assess if the "shape" was correctly draw or not.

Basic example:

 var foo = document.getElementById('foo'), x = -1, y = -1; function between(n, en, err) { return (n >= en - err && n <= en + err); } function fail() { // user failed so do stuff accordingly console.warn('User failed to draw properly'); // reset stuff x = -1; y = -1; } foo.addEventListener("mouseenter", function(event) { console.log('enter: ' + event.x + ',' + event.y); if (x === -1) { // first enter, so check if user started in the correct position // This is tied to the position of the canvas, if the user must start at the beginning // of the path or he can start wherever... // so you should implement your own logic return; } // Check if drawing is complete // Onde again, same as above // check if after the first mouseleave, the mouseenter event was // in an acceptable range if (!between(x, event.x, 10) || !between(y, event.y, 10)) { fail(); } }); foo.addEventListener("mouseleave", function(event) { console.log('exit: ' + event.x + ',' + event.y); x = event.x; y = event.y; }); 
 <svg> <path id="foo" d="M100,100 L150,100 a50,25 0 0,0 150,100 q50,-50 70,-170 Z" stroke-width="20" style="stroke: red; fill: none;" /> <path d="M100,100 L150,100 a50,25 0 0,0 150,100 q50,-50 70,-170 Z" style="stroke: #006666; fill: none;" /> </svg> 

For instance, in this example I accept an "error" of 10px. So I set the stroke of the hidden path to 20px.

When the user mouse leaves the accepted drawing area, if it not reenters in an acceptable range, it fails the drawing and resets.

This is just an example, but you can build from this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM