admin管理员组

文章数量:1323342

I am trying to do an exercise in data visualization using the browser to plot the contents of a local text file. Both the html and the txt are local, and it is for prototyping/personal-use only.

Basically, I would want to use, say, javascript, to read a file just like this:

0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
0.0, 0.2, 0.3, 0.3, 0.3, 0.2, 0.0
0.0, 0.3, 0.5, 0.6, 0.5, 0.3, 0.0
0.0, 0.3, 0.6, 0.8, 0.6, 0.3, 0.0
0.0, 0.3, 0.5, 0.6, 0.5, 0.3, 0.0
0.0, 0.2, 0.3, 0.3, 0.3, 0.2, 0.0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0

and render as a square grid of colored circles. Each value from the txt would be the opacity of the correspondent circle, like this (made using Python, Numpy, Cairo and PIL):

I am a plete beginner on javascript and HTML5 Canvas, so I would appreciate very much a clue so as to what I should do, which functions to use, etc.

There's no need to give plete code (but it would be nice!), just the name of the functions and concepts, so that I can look for tutorials and assemble my Frankenstein from a bunch of "Hello Worlds", or anything like that.

Thanks for reading!

I am trying to do an exercise in data visualization using the browser to plot the contents of a local text file. Both the html and the txt are local, and it is for prototyping/personal-use only.

Basically, I would want to use, say, javascript, to read a file just like this:

0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
0.0, 0.2, 0.3, 0.3, 0.3, 0.2, 0.0
0.0, 0.3, 0.5, 0.6, 0.5, 0.3, 0.0
0.0, 0.3, 0.6, 0.8, 0.6, 0.3, 0.0
0.0, 0.3, 0.5, 0.6, 0.5, 0.3, 0.0
0.0, 0.2, 0.3, 0.3, 0.3, 0.2, 0.0
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0

and render as a square grid of colored circles. Each value from the txt would be the opacity of the correspondent circle, like this (made using Python, Numpy, Cairo and PIL):

I am a plete beginner on javascript and HTML5 Canvas, so I would appreciate very much a clue so as to what I should do, which functions to use, etc.

There's no need to give plete code (but it would be nice!), just the name of the functions and concepts, so that I can look for tutorials and assemble my Frankenstein from a bunch of "Hello Worlds", or anything like that.

Thanks for reading!

Share Improve this question edited Dec 7, 2011 at 17:30 heltonbiker asked Dec 7, 2011 at 17:07 heltonbikerheltonbiker 27.6k30 gold badges149 silver badges268 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

TL;DR : http://bv.iriscouch./so/_design/ex/index.html and http://bv.iriscouch./so/_design/ex/separate-function.html

This is a slightly verbose answer but I feel like I was in your shoes not too long ago, and would have benefitted from some of the below pointers. I will target it with Python analogies since you mentioned those Python libraries. Also feel like mentioning: I like low-level stuff, I love oscilloscopes, C, etc., but the beautiful, lower-level heart of javascript is its objects and functions -- the browser environment is a jungle and I am much happier since handing off as much as possible to jQuery and Underscore.js.

First, regarding csv format, if it's an absolute requirement use something like d3.csv from the d3.js library. (In fact, regard all data vizualization javascript you learn from now forward as preparation for copying as much as possible from the imagination of Mike Bostock.) But asking about csv in Javascript is a bit like asking "I'm new to Asia, where is the best place to get sushi in Sichuan?" Answer: "You're in Sichuan!!!". Use json. In python in your case I would just do:

>>> f = open('sample.csv').readlines()
>>> rv = json.dumps([[float(i) for i in k.split(',')] for k in f])
>>> file_out.write(rv)

Here is how you do it in one piece: http://bv.iriscouch./so/_design/ex/index.html

Here is how you might break it up into the core function that then gets rendered on the page's canvas: http://bv.iriscouch./so/_design/ex/separate-function.html

(Parenthetically, try iriscouch., it is one of the coolest things on the internet, and a good way to get familiar with Javascript. The below examples are there. sudo pip install couchapp, couchapp generate ex, cp *.js *.html ex/_attachments, cd ex && couchapp push https://user:[email protected]/somename is how I put up these examples, totally free. Windows installer here.)

If you want to look at the underlying data as reformatted, that's here.

Finally, you can see more of my personal babysteps in this stuff at http://aguacat.es

Inline of above example:

<!doctype html>

<html>
  <head>
    <script src="jquery.js"></script>
  </head>
  <body>
    <canvas id="circles" height="700" width="700"></canvas>
    <script>
      // $ is just a function. It makes dealing with the
      // browser itself less annoying. Call it with a
      // function as argument. The function has no
      // name, like a python lambda, and it will
      // request the json and process it.
      $(function () {
        var the_color = "rgba(0,0,255,alpha_token)";
        // ask for the json and register the following
        // function (second argument to getJSON) to be called 
        // once it is delivered:
        $.getJSON('json_from_csv.json', function(data) {
          // no more jquery for now
          var canvas = document.getElementById("circles");
          // you declare these to avoid them being global variables:
          var h, w, column_width, column_height, x_pos, y_pos, radius;
          h = canvas.height;
          w = canvas.width;
          column_width = w / data[0].length;
          column_height = h / data.length;
          // we're working in 2 dimensions:
          var context = canvas.getContext('2d');
          radius = column_width / 2; 
          data.forEach(function (row, row_index) {
            row.forEach(function (entry, column_index) {
              x_pos = column_index * column_width + radius;
              y_pos = row_index * column_height + radius;
              context.moveTo(x_pos, y_pos);
              context.beginPath();
              context.arc(x_pos, y_pos, radius, 0, Math.PI*2)
              context.fillStyle = the_color.replace(/alpha_token/, entry);
              context.strokeStyle = the_color.replace(/alpha_token/, entry);
              context.fill();
              context.stroke();
              context.closePath();
            });
          });
          });
        });
      </script>
    </body>

</html>

Responding to Heltonbiker. It's very possible to store acces data locally with javascript, for example you could create a json object store it in a var and save the file locally. Your file would look something like:

var jsonObject = {

    "priorities": [ [1,12], [4,2] ]
}

Now if you include your local file in the head of your script as such:

<script type="text/javascript" language="javascript" src="priorities.json"></script>

Now I can acces data from my index.html stored in the same directory to manipulate my canvas.

Jeffrey thank you for the helpfull articles I'm looking for a way to draw a plot from two datasets in pure javascript no libraries and this was some nice info on that :)

It's very possible!

You can read local text files through JavaScript via the xmlhttprequest object, and parse its contents with regular expressions or a similar method.

Unfortunately, I'm not very good with string parsing, but I whipped up this example for loading a file and drawing circles on a canvas.

script.js:

var Visualizer =  {

    canvas      : document.getElementById("canvas"),
    context     : this.canvas.getContext("2d"),
    fileContents    : "",

    //Load a local file
    loadFile    : function(address) {
        var file = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
        if(file == null) {
            console.log("Error: XMLHttpRequest failed to initiate.");
        }
        file.onreadystatechange = function() {
            if (file.readyState == 4) { //Completed loading
                if (file.status == 200 || file.status == 0) {

                    //The responseText is the contents of the text file
                    fileContents = file.responseText;

                    Visualizer.onFileLoad();
                }
                else    //Otherwise, there was a problem while loading
                    console.log("Error " + file.status + " has occurred.");
            }
        }
        try {
            file.open("GET", address, true);
            file.send(null);

        } catch(e) {
            console.log("Error retrieving data file. Some browsers only accept cross-domain request with HTTP.");
        }

    },

    //Called when the xmlhttprequest object loads the file successfully
    onFileLoad  : function() {
        this.parseFile();
    },

    //Iterates through a file and draws circles
    parseFile   : function() {

        var x = 0;
        var y = 0;


        //~~~Create some method for parsing the text~~~

        var r = 100;
        var g = 100;
        var b = 255;

        var color = "rgba("+r+","+g+","+b+",1)";

        this.drawCircleAt(x+25, y+25, color);



    },


    //Draws circles with a 25 pixel diameter at the position specified.
    drawCircleAt    : function(x, y, color) {

        this.context.fillStyle = color;
        this.context.beginPath();
        this.context.arc(x, y, 25, 0, 6.283, false);
        this.context.fill();
        this.context.closePath();

    }


}

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <canvas id="canvas" width="500" height="500">
        </canvas>
        <script type="text/Javascript" src="script.js"></script>
        <script>
            Visualizer.loadFile("file.txt");
            </script>
    </body>
</html>

If you have any questions about the code, ask away.

本文标签: javascriptUse HTML5 Canvas to quotplotquot 2d array from local csvStack Overflow