简体   繁体   English

如何将像素转换为measurement-html5 canvas

[英]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.如果我的画布反映了一些现实生活中的测量值,例如 8 米乘 6 米,并且我在其上画了一条线,我如何计算画布上那条线的测量值。 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.即,如果我从位置 x1,y1 绘制到位置 x2,y2,我会测量它并确定它的长度约为 x 长度。 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.我正在使用带有 javascript atm 的只有 1 个画线功能的简单画布。

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.如果画布的尺寸比例与其应表示的区域的测量比例(以米为单位)相匹配,则您只需计算一次 MPP(宽度或高度),您就可以计算总线长,而无需组件。

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:要在屏幕上显示长度:只需添加一个 'div' 或 'span' 或其他任何内容,然后在其中写入如下行:

HTML: HTML:

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

Javascript: 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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