IlludiumPu36
IlludiumPu36

Reputation: 4304

Drawing consistant line length against ruler using Fabric.js

I have a horizontally scrollable div which contains another div (id ruler) and a canvas.

On the canvas, I am drawing a horizontal line, which will have different lengths.

I need to draw the line so that the length is consistently measurable against the ruler rendered using javascript and css in the ruler div:

 var canvas = new fabric.Canvas('canvas');

line_length = 14000;

adjusted_length = line_length / 6.367;

canvas.add(new fabric.Line([100, 100, adjusted_length, 100], {
        left: 30,
        top: 50,
        stroke: '#d89300',
        strokeWidth: 2
    }));

    $('#canvas_container').css('overflow-x', 'scroll');
    $('#canvas_container').css('overflow-y', 'hidden');

    drawRuler();


function drawRuler(){
    $("#ruler[data-items]").val(line_length / 200);

    $("#ruler[data-items]").each(function() {
        var ruler = $(this).empty(),
            len = Number($("#ruler[data-items]").val()) || 0,
            item = $(document.createElement("li")),
            i;
            ruler.append(item.clone().text(1));
        for (i = 1; i < len; i++) {
            ruler.append(item.clone().text(i * 200));
        }
        ruler.append(item.clone().text(i * 200));
    });
}

So, if the line length is 14000, I'm dividing that by 6.367 to get the length of the line reaching 14000 on the ruler.

But if the line length is 6600, I need to divide that by something like 6.1 to get the length reaching to 6600 on the ruler.

The question is how do I handle this so that different line lengths are properly measured against the ruler?

Best see the fiddle at http://jsfiddle.net/dH962/

Upvotes: 1

Views: 3259

Answers (1)

IlludiumPu36
IlludiumPu36

Reputation: 4304

That wasn't too hard, all I had to do was work out what a line of 100 pixels measured out to on the ruler. The answer was 666 (yes, the number of the devil...). So then:

adjusted_length = (line_length / 666) * 100;

Gives the correct measure against the ruler for varying line lengths

Working Fiddle at http://jsfiddle.net/Uu4TD/1/

Also I fixed an error with the coordinates when drawing the line...so now:

canvas.add(new fabric.Line([0, 0, adjusted_length, 0], {
        left: 28,
        top: 50,
        stroke: '#d89300',
        strokeWidth: 2
    }));

Upvotes: 1

Related Questions