小时候都玩过数字连线画册,这里我们用canvas将它实现
逻辑要点:
- canvas无法进行回撤操作,即每一步都需要完整的重新绘制
- 为了体验更好此处做了一个简单的矩形范围吸附效果,完善可以更改成圆形范围
演示链接:
点我
源码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>小互动-数字连线</title>
<meta name="viewport"
content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1,viewport-fit=cover">
</head>
<style>
body {
background-color: gray;
}
#canvas {
position: absolute;
background-image: url(./numconnect.jpeg);
}
</style>
<body style="margin:0;padding:0;" ontouchmove="javascript:window.event.preventDefault();">
<canvas id="canvas" width="300" height="426"></canvas>
</body>
<script type="text/javascript">
let points = [
101, 340,
58, 356,
16, 292,
61, 10,
46, 294,
106, 179,
196, 140,
224, 120,
275, 146,
287, 184
]
let cv = document.getElementById('canvas');
let ctx = cv.getContext("2d");
let connectOver = false;
let curIndex = 0;
let limit = 10;
draw();
function draw() {
ctx.clearRect(0, 0, cv.width, cv.height);
for (let index = 0; index < points.length; index += 2) {
const x = points[index];
const y = points[index + 1];
if (index > 0 && index <= 2 * curIndex) {
drawLine(ctx, points[index - 2], points[index - 1], x, y)
}
drawPoint(ctx, x, y);
}
}
function drawLine(ctx, sx, sy, ex, ey) {
ctx.beginPath()
ctx.moveTo(sx, sy)
ctx.lineTo(ex, ey);
ctx.lineWidth = 4;
ctx.strokeStyle = '#000';
ctx.stroke();
}
function drawPoint(ctx, cx, cy) {
let R = 4
ctx.save();
ctx.fillStyle = '#000';
ctx.beginPath();
ctx.arc(cx, cy, R, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
document.addEventListener('mousedown', onDocumentMouseDown, false);
function onDocumentMouseDown(event) {
event.preventDefault();
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
}
function onDocumentMouseMove(event) {
var x = event.clientX;
var y = event.clientY;
moveEvent(x, y);
}
function onDocumentMouseUp() {
upEvent();
document.removeEventListener('mousemove', onDocumentMouseMove);
document.removeEventListener('mouseup', onDocumentMouseUp);
}
document.addEventListener('touchstart', onDocumentTouchStart, false);
document.addEventListener('touchmove', onDocumentTouchMove, false);
document.addEventListener('touchend', onDocumentTouchEnd, false);
function onDocumentTouchStart() {
}
function onDocumentTouchMove(event) {
let x = event.changedTouches[0].clientX;
let y = event.changedTouches[0].clientY;
moveEvent(x, y);
}
function onDocumentTouchEnd(event) {
upEvent();
}
function moveEvent(x, y) {
if (connectOver) {
return;
}
draw();
drawLine(ctx, points[2 * curIndex], points[2 * curIndex + 1], x, y);
let tx = points[2 * (curIndex + 1)];
let ty = points[2 * (curIndex + 1) + 1];
if (Math.abs(x - tx) < limit && Math.abs(y - ty) < limit) {
curIndex += 1;
draw();
}
if (curIndex == points.length / 2 - 1) {
connectOver = true;
alert("连完了")
}
}
function upEvent() {
if (connectOver) {
return;
}
draw();
}
</script>
</html>
网友评论