0

私が現在作成しようとしているのは、データを視覚化する座標系です。既存のフレームワークを使いたくないが、ゼロから作成したい。

私が持っているのは、(15, 20)、(-5,1)、(120,-17) などの 3 つのポイントです。彼らは、座標系のスケールを x-min = -5 および x-max = 120 および y-min = -17 および x-max = 20 で定義します。この例では、10 ごとに 1 つのマークで (-100, -100) から (100,100) に到達する座標系を持つことは意味がありません。

<html>
<head>
<script type="text/javascript">
function drawShape(){
  var canvas = document.getElementById('mycanvas');

  if (canvas.getContext){

    //draw canvas
    var context = canvas.getContext('2d');

    var canvasBorder = Math.floor(canvas.scrollHeight * 0.1);
    var xLength = Math.floor(canvas.scrollWidth - (canvasBorder * 2));
    var yLength = Math.floor(canvas.scrollHeight - (canvasBorder * 2));

    //draw coordinate system
    context.beginPath();
    context.moveTo(canvasBorder, canvasBorder);  //30,30
    context.lineTo(canvasBorder, canvasBorder + yLength); //30,270
    context.lineTo(canvasBorder + xLength, canvasBorder + yLength); //370,30
    context.stroke();

    //easy: define 5 values for x-axis
    var xMaxValue = 5;
    var tmp = Math.floor(xLength / xMaxValue);

    for(i = 0; i <= xMaxValue; i++){
        context.beginPath();
        context.moveTo(canvasBorder + tmp*i, canvasBorder + yLength);
        context.lineTo(canvasBorder + tmp*i, canvasBorder + yLength+10);
        context.fillText(i, canvasBorder + tmp*i, canvasBorder + yLength+10);
        context.stroke();
    }

    //difficult: have a max value for y-axis
    //too much space between 117 and 200, should display 120 or 150 instead
    //next level, what happens with -20 instead of 0 for min-y
    var yMaxValue = 117;
    var yIncrement = Math.pow(10, (Math.abs(Math.floor(yMaxValue)).toString().length)) / 10;
    var topValue = Math.floor(yMaxValue / yIncrement) + 1;

    var tmp = parseInt(yLength / topValue);

    for(i = 0; i <= topValue; i++){
        context.beginPath();
        context.moveTo(canvasBorder, yLength + canvasBorder - tmp*i);
        context.lineTo(canvasBorder - 10, yLength + canvasBorder - tmp*i);
        context.fillText(yIncrement * i, canvasBorder - 10, yLength + canvasBorder - tmp*i);
        context.stroke();
    }


  } else {
    alert('You need Safari or Firefox 1.5+ to see this demo.');
  }
}
</script>


</head>

<body onload="drawShape();">
<canvas id="mycanvas" width="400" height="300"
style="border:1px solid #ddd;">
</canvas>


</body>

</html>

または、それに応じてデータを取得して座標系を作成するより良い方法はありますか?

乾杯、フロリアン

4

1 に答える 1

1

チャートに表示するために、実際の値をより伝統的な範囲にマップしたいようです。

たとえば、次のように仮定します。

  • 実際の値の範囲は -17 から 120 です。

  • これらの実際の値を、より伝統的な 0 ~ 100 の範囲にマップします。

これは、実際の範囲の値を別の範囲にマップする関数です。

function remap(value, actualMin, actualMax, newMin, newMax) {
    return(newMin + (newMax - newMin) * (value - actualMin) / (actualMax - actualMin);
}

たとえば、実際の値 33 (-17 ~ 120 の範囲) を 0 ~ 100 の範囲に再マップするには、次のようにします。

remappedValue = remap( 33,  -17,120,  0,100 );

0 ~ 100 の新しい範囲の例は単なる例であることに注意してください。

newMin から newMax までの任意の範囲を使用できます。

于 2013-10-30T02:49:59.573 に答える