使用 html5 canvas 元素,将图像设置为 canvas 元素的 css 背景(使绘制线条更容易,因为您不必重新绘制图像)并在画布上绘制线条:
1) On mousedown
,记录鼠标位置并注册一个mousemove
处理程序围绕这些起始位置关闭,并注册一个mouseup
处理程序删除mousemove
处理程序。
2)在mousemove
处理程序,找到当前鼠标位置和鼠标起始位置之间的偏移量,将此偏移量添加到起始行位置,然后使用此新位置重新绘制画布。
您无法用物理距离来标记线条,因为这取决于显示您的作品的屏幕。您能做的最好的事情就是确定图像的比例/打印分辨率(以 dpi 为单位,例如每英寸 300 像素),并据此计算线条的长度。确切的实现取决于您想要如何使用结果。
更新:示例
演示JSFiddle
HTML
<canvas id="canvas" width="200" height="200">
Your browser doesn't support canvas
</canvas>
CSS
canvas{
background-image: url("image.jpg");
background-position: center;
background-size: 100% 100%;
}
JS
$(document).ready(function(){
var imageDpi = 300;
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var startX, startY;
$("canvas").mousedown(function(event){
startX = event.pageX;
startY= event.pageY;
$(this).bind('mousemove', function(e){
drawLine(startX, startY, e.pageX, e.pageY);
});
}).mouseup(function(){
$(this).unbind('mousemove');
});
function drawLine(x, y, stopX, stopY){
ctx.clearRect (0, 0, can.width, can.height);
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(stopX, stopY);
ctx.closePath();
ctx.stroke();
// calculate length
var pixelLength = Math.sqrt(Math.pow((stopX - x),2) + Math.pow((stopY-y),2));
var physicalLength = pixelLength / imageDpi;
console.log("line length = " + physicalLength +
" inches (image at " + imageDpi + " dpi)");
}
});
更新 2:线路长度
我更新了我的例子。它定义图像的物理分辨率并根据该假设计算线条的长度。