Draw a line on an Image using javascript

前端 未结 1 1271
南旧
南旧 2021-01-21 18:05

I have an image in html img tag. My requirement is that when a user click on the image it will mark a point and draw a line while dragging the mouse. Then, While user finishes t

1条回答
  •  鱼传尺愫
    2021-01-21 18:50

    Use the html5 canvas element, set the image as a css background to the canvas element (makes drawing the lines easier because you don't have to redraw the image) and draw the line on the canvas:

    1) On mousedown, record the mouse position and register a mousemove handler closed around those starting positions, and register a mouseup handler to remove the mousemove handler.

    2) In the mousemove handler, find the offset between the current mouse position and the mouse's starting position, add this offset to the starting line position and then redraw the canvas using this new position.

    You can't label the line with a physical distance because this will depend on the screen that displays your work. The best you can do is decide on a scale/print resolution for your image (in dpi, e.g. 300 pixels per inch) and calculate the length of the line based on that. The exact implementation depends on how you want to use the results.

    UPDATE: EXAMPLE

    DEMO JSFIDDLE

    HTML

    
        Your browser doesn't support 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)");
        }
    });
    

    UPDATE 2: LINE LENGTH

    I updated my example. It defines the image's physical resolution and calculates the line's length based on that assumption.

    0 讨论(0)
提交回复
热议问题