Reputation: 93
We are creating educational material and need a matching app. 5 English words on one side of screen + 5 boxes of Spanish words on the other. We are using HTML5 + CSS + javascript. The student will draw a line with cursor or finger from the left hand side box to the correct translation box to the right hand side. ie: Simple matching app. The code below draws a specific line but I want to create a dynamic line that follows the cursor/finger. The I suppose I need js to detect whether the boxes match. Thank you in advance for any help.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Color Lines</title>
</head>
<body>
<canvas id="DemoCanvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById('DemoCanvas');
if (canvas.getContext)
{
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(100, 10);
context.lineTo(100, 200);
context.lineWidth = 5;
// set line color
context.strokeStyle = '#808000';
context.stroke();
}
</script>
</body>
</html>
Upvotes: 0
Views: 958
Reputation: 36565
Using canvas would be one way of drawing the lines, but it can get a bit messy as you have to redraw the whole path after clearing the canvas each time.
If canvas is not a requirement, a simple way of drawing a line between two points it to have a div element which gets its length and its rotation from the two endpoints. You do the bit of math in Javascript like:
let line= document.querySelector('.line');
function drawLine(x1, y1, x2, y2) {
var length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
line.style.transform = 'rotate('+angle+'deg)';
line.style.width = length;
line.style.height = '2px';
line.style.left = x1 + 'px';
line.style.top = y1 + 'px';
line.style.backgroundColor = 'red';
}
drawLine( 100, 100, 250, 250);
<div class="line"></div>
In your case you will want each English word's element to have a line element associated with it (perhaps as a child div - but I don't know the structure of your HTML) and the current line to be selected when the student touches or mousedowns on the word, remember the x1, y2 then on mousemove (on the window) if there is a currently selected word, read the position of the finger or mouse and call drawLine for the currently selected word's line.
You can have a mouseout or touchend event on the Spanish words to sense when they have been selected.
Upvotes: 1