1

Please help me. There is a javascript code, where I make a canvas graph. The data for the graph is there static, but I want to load these datas from a .txt file. Do you know how? Thank you!

<script type="text/javascript">

var canvas ;
var context ;
var Val_max;
var Val_min;
var sections;
var xScale;
var yScale;



        // Values for the Data Plot, they can also be obtained from a external file
var data =[0,10,20,40,50,100,120,130,0];



function init() {
        // set these values for your data 
    sections = 12;
    Val_max = 130;
    Val_min = -40;
    var stepSize = 10;
    var columnSize = 50;
    var rowSize = 50;
    var margin = 10;
    var xAxis = [" ", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] 
        //

    canvas = document.getElementById("canvas");
    context = canvas.getContext("2d");
    context.fillStyle = "#0099ff"
    context.font = "20 pt Verdana"

    yScale = (canvas.height - columnSize - margin) / (Val_max - Val_min);
    xScale = (canvas.width - rowSize) / sections;

    context.strokeStyle="#009933"; // color of grid lines
    context.beginPath();
        // print Parameters on X axis, and grid lines on the graph
    for (i=1;i<=sections;i++) {
        var x = i * xScale;
        context.fillText(xAxis[i], x,columnSize - margin);
        context.moveTo(x, columnSize);
        context.lineTo(x, canvas.height - margin);
    }

1 Answer 1

1

For load file, try this:

function request (path, onload) {
    var req = new XMLHttpRequest();
    req.onload = function () {
        return onload(this.responseText);
    };
    req.open("GET", path, true);
    req.send();
}

and use:

request('http://yousite.com/text.txt',function(response){
    //code here
});
Sign up to request clarification or add additional context in comments.

2 Comments

And what will be in the function response? Why is this here?
@MílaSkipperMoravec Response is a content of file of url request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.