这里提供一个基于 JavaScript 的在线 CAD 测量长度功能示例代码:- <!DOCTYPE html>
- <html>
- <head>
- <title>在线 CAD 测量长度功能</title>
- <meta charset="utf-8">
- <style type="text/css">
- canvas {
- border: 1px solid black;
- cursor: crosshair;
- }
- </style>
- </head>
- <body>
- <canvas id="canvas" width="400" height="400"></canvas>
- <script type="text/javascript">
- // 初始化变量
- var canvas = document.getElementById('canvas');
- var context = canvas.getContext('2d');
- var mouseDown = false;
- var lastX, lastY;
- var currentX, currentY;
- var totalLength = 0;
- // 监听鼠标按下事件
- canvas.addEventListener('mousedown', function(event) {
- mouseDown = true;
- lastX = event.pageX - canvas.offsetLeft;
- lastY = event.pageY - canvas.offsetTop;
- context.beginPath();
- context.moveTo(lastX, lastY);
- });
- // 监听鼠标移动事件
- canvas.addEventListener('mousemove', function(event) {
- if (mouseDown) {
- currentX = event.pageX - canvas.offsetLeft;
- currentY = event.pageY - canvas.offsetTop;
- context.lineTo(currentX, currentY);
- context.stroke();
- totalLength += Math.sqrt(Math.pow((currentX - lastX), 2) + Math.pow((currentY - lastY), 2));
- lastX = currentX;
- lastY = currentY;
- }
- });
- // 监听鼠标抬起事件
- canvas.addEventListener('mouseup', function(event) {
- mouseDown = false;
- alert('总长度为:' + totalLength.toFixed(2) + ' 像素');
- });
- </script>
- </body>
- </html>
复制代码 在该示例代码中,我们首先获取了 canvas 元素和其绘图上下文对象 context。然后监听了 mousedown、mousemove 和 mouseup 三个事件,并在事件处理函数中实现了绘制线条并计算总长度的逻辑。最后,当鼠标抬起时,弹出一个提示框展示总长度。 需要注意的是,在这段示例代码中,长度的单位是像素,如果需要将其转换为其他单位(如毫米、英寸等),则需要根据实际情况进行换算,详细情况可以参考梦想CAD控件的H5云图版产品。
|