View Full Version : Graphs with just HTML and PHP

10-12-2012, 06:22 AM
I'm working on an ongoing project where I need up-to-date graphs from my database and I need to be able to control what they look up.
After hours of messing with trigonometry today (among other things) I finally got a working graph utility going in PHP.

Basically it allows you to create points in the X,Y space (note that Y is top-down in HTML, so it must be inverted here, subtracted from height), and (the really tricky part) also add lines between them.

I ended up using 1px high divs for the lines rather than an HR due to the annoying default styles on HRs. Also, this hasn't been fully cross browser tested (and relies on perhaps limited rotation methods available)-- but it works in Safari and Firefox at least.

So here's the code:
$points = array(

function drawhtmlline($x1,$y1,$x2,$y2) {
$rise = $y2-$y1;
$run = $x2-$x1;
$length = sqrt(pow($rise,2)+pow($run,2));
$angle = 180-round(rad2deg(atan($rise/$run)));
$xoffset = abs(($length/2)-abs($run/2));//fix from rotating from center of object
echo '<div style="background-color:red;height:1px;width:'.round($length).'px;position:absolute;top:'.round(200-$y2+($rise/2)-2).'px;left:'.round(2+$x2-$xoffset).'px;-moz-transform:rotate('.$angle.'deg);-webkit-transform:rotate('.$angle.'deg);-o-transform:rotate('.$angle.'deg);-ms-transform:rotate('.$angle.'deg);transform:rotate('.$angle.'deg);"></div>';

<title>HTML &amp; PHP Graph Demo</title>
<div style="position:relative;width:200px;height:200px;background-color:#CCCCCC;border:1px solid black;">
foreach($points as $pk=>$point) {
<div style="background:red;position:absolute;top:<?php echo (-4)+200-($point[1]); ?>px;left:<?php echo $point[0]; ?>px;width:4px;height:4px;"></div>
if ($pk!==0) {

Which outputs the following graph (here shown as an image). Remember-- this is pure HTML and PHP (plus inline CSS). No images are used whatsoever.

If anyone wants more info on how to use this, let me know. But in short, just setup a new .php file with that as the code and play with it to see how it works. Not much documentation yet, so this is for somewhat experienced PHP users-- that's necessary anyway for you to setup whatever you actually need it to do.