简体   繁体   中英

how to convert pixels into measurement-html5 canvas

if my canvas is reflecting some real life measurements like 8 meter by 6 meter and i draw a line on it, how can i calculate the measurement of that line on canvas. ie if i draw from position x1,y1 to position x2,y2 i measure it and say for sure that it is approximately x length long. Also will it be possible to show the measurement right below the line on runtime too like as soon as i finish the line,its length is automatically be shown at bottom of it. i am using simple canvas with just 1 draw line function with javascript atm.

var linePixelsX = x2-x1;
var linePixelsY = y2-y1;
// horizontal/vertical components of line in pixels

var horizontalMPP = ( m / p );
var verticalMPP = ( m / p );
// horizontal/vertical meters per pixel, p being according canvas measurement in pixels and m being the measurement (in meters) of the area it should represent

var lineMetersX = linePixelsX * horizontalMPP;
var lineMetersY = linePixelsY * verticalMPP;
// calculate horizontal/vertical line components in meters

var lineMetersTotal = Math.SQRT2(lineMetersX*lineMetersX + lineMetersY*lineMetersY);
// Calculate total line length in meters with some Pythagoras

You have to split the line into its horizontal and vertical components, as if it were a vector.

If the proportion of the dimensions of your canvas matches the proportions of the measurements (in meters) of the area it should represent, you only have to calculate the MPP once (with either width or height) and you can calculate the total line length without the components.

Some simple scaling math and vectors here :)

For displaying the length on screen: just add a 'div' or 'span' or whatever and write the line in it like following:

HTML:

<canvas>
</canvas>
<div id="lengthDiv"></div>

Javascript:

function drawLine(){
// All other stuff + what I showed above

document.getElementById('lengthDiv').innerHTML = lineMetersTotal;
// get 'div' by ID and assign your length to innerHTML
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM