Tải bản đầy đủ - 0 (trang)
Hack 137. Visualize Traffic with DIY Vector Graphics

Hack 137. Visualize Traffic with DIY Vector Graphics

Tải bản đầy đủ - 0trang




...



Then,inthesectionoftheHTML,includealinktoa

JavaScriptfile,whichyouwillusetodrawtheline(you'llcreate

thisshortly).Also,insertanonloadcalltothefunctionmain()

inthebodytag,asshownhere(I'malsoaddinganinlinestyle;

pleaseincludeyourownexternalstylesheettodefinethepage

layoutasyouseefit[Hack#18]):

...

Drawingaline










...



Next,createadefault.jsfilecontainingthefollowingJavaScript,

andputitinthesamefolderasindex.html:

functionmain(){

//grabthecanvas

varcanvas=document.getElementById('picture');

varctx=canvas.getContext('2d');

//setthecolorandlinewidth

ctx.strokeStyle='rgba(40,200,180,1)';

ctx.lineWidth=8;

//drawaline

ctx.beginPath();

ctx.moveTo(40,140);

ctx.lineTo(240,40);

ctx.stroke();

}



That'snotalotofcode—you'regrabbingthecanvaselement

usingtheIDyoudefined(picture),thenyou'reconfiguringthe

linestyle,andthenyou'removingthelinefromstartpoint(x

andy)toendpoint.Nowopenyourindex.htmlfileinarecent

versionofOpera,Firefox,orSafari,andyouwillseethataline

isdrawn,asshowninFigure12-15!Ifyoucan'tseealine,it's

timetoopenthedebuggingwindow;inFirefox,chooseTools

ErrorConsolefromthemenu.

GettingCanvastoWorkinInternetExplorer

Butwaitasecond.Didn'tIpromisethiswouldworkinInternet

Exploreraswell?Nowhere'sthecaveat:InternetExplorer

doesn'tnativelysupportCanvasyet.Beforeyoutearyourhair

out(ormine),orprepareanastylettertoO'Reillyaskingfor



yourmoneyback,letmeexplain!ThankstoabunchofGoogle

developers,it'sveryeasytogetIE7tosupportCanvas,because

thesedevelopers(EmilA.Eklund,ErikArvidsson,andGlen

Murphy)wroteaJavaScriptlibrarythatemulatesCanvasinIE's

nativevectorlanguage,VML(shortforVectorMarkup

Language,nottobeconfusedwithVRML,theVirtualReality

Markup/ModelingLanguage).

YoucangetExplorerCanvasfrom

http://excanvas.sourceforge.netbyfollowingthelinkstothe

download.DroptheJavaScriptfileinthesamefolderasyour

index.html,andlinkitfromtheHTMLasshownhere.Usingthe

conditionalcommentsmeansthatyouwon'tbeburdeningany

otherbrowserbutIEwiththe10KBthefileismadeupof,inits

compressedfileversion:

Drawingalineusing



...







...



Phew...youarenowreadytoopenindex.htmlinInternet

Explorer,too.



DrawingaTrafficChartinCanvas

NowthatyouknowhowtosetupCanvas,evenifonlytodraw

asimpleline,you'veopenedthedoortoawholeuniverseof

vectorart!Let'susethisknowledgetovisualizetrafficdatafrom

GoogleAnalytics.Logintooneofyourwebsitestatsat

http://analytics.google.comandchooseVisitors Visitor

Trending Visits.ClicktheExportbuttonandsavetheXML

downloadasstats.xml.

YoucanopentheXMLfileinyourbrowsertohavealook—it

consistsof,amongotherdata,pointvaluesshowingvisitsfor

thelast30days:

...



29,430







24,058





...



ToloadthisXMLfileusingJavaScript,youcanuseAjax

(AsynchronousJavaScriptandXML,awayforwebpagestopull

remotedatawithouttheneedforafullpagereload).Atthis

point,afterchangingthefiles,uploadthemtoyourserveror

runthemonaserveronyourcomputer—likeWAMP,anApache

installationforWindows(http://wampserver.com)—sothatthe

browserwillgrantthescripttherightstograbtheXMLfile.This

examplewon'tworkifyouloaditasafile://URL.

Tocontinue,I'mamendingthefilesthatwerepreviouslyused

fordrawingaline(youcanalsocopytheexistingfilesintoa

newfolderandthenamendthecopies,ifyouprefer).Replace



theentireJavaScriptsothatitnowreadsasfollows:

CodeView:



functionmain(){

//grabtheXMLviaAjax,usingdifferentmethods,dependin

varurl='stats.xml';

if(window.XMLHttpRequest){

req=newXMLHttpRequest();

}

elseif(window.ActiveXObject){

req=newActiveXObject('Microsoft.XMLHTTP');

}

req.onreadystatechange=receiveChart;

req.open('GET',url,true);

req.send(null);

}

functionreceiveChart(){

//parsetheXMLintoanarray,removingcommasfrom

//numbers,andpassittodrawChart

























CodeView:

if(req.readyState==4){

if(req.status==200){

vartimeFrame=30;

vard=req.responseXML.getElementsByTagName('Value');

varvalues=newArray();

for(vari=0;i
varvisits=d[i].firstChild.data;

values[i]=parseInt(visits.replace(/,/g,''));

}

drawChart(values);

}



}

}

functiondrawChart(values){

//drawthechartwhilenormalizingthedisplayof

//thelinesbasedonthepeakvalueofthearray

varpeak=getMaxValueOfArray(values);

varcanvas=document.getElementById('picture');

varctx=canvas.getContext('2d');

ctx.strokeStyle='rgba(40,200,180,1)';

ctx.lineWidth=5;

ctx.beginPath();

ctx.moveTo(0,canvas.height);

for(vari=0;i
varpercent=getPercent(peak,values[i]);

varx=i*(canvas.width/(values.length-1));

vary=(100-percent)*(canvas.height/100);

ctx.lineTo(Math.round(x),Math.round(y));

}

ctx.lineTo(canvas.width,canvas.height);

ctx.lineTo(0,canvas.height);

ctx.stroke();

}

functiongetMaxValueOfArray(values){

varmax=0;

for(vari=0;i
if(values[i]>max){

max=values[i];

}

}

returnmax;

}

functiongetPercent(all,part){

returnall>0?100/all*part:0;

}



























Loadindex.htmlinyourbrowsertoseeachartsimilartothe

oneshowninFigure12-16.Therearestillthingslefttobedone

tofine-tunethescript,suchas:

Errorhandlingtoalertyouwhensomethingiswrongwith

theXML.

PreventingtheXMLfrombeingcachedtooquicklyincase

youwanttoupdateit.

Prettifyingthechartoranimatingit.

buthopefully,thisexamplehasyoureadytodelvedeeperinto

Canvas!



DrawingaCanvaschartbasedonyourGoogleAnalytics

statistics



NOTE

FormanymoreCanvassamples,checkout

http://developer.mozilla.org/en/docs/Category:Canvas_examples



Hack138.TalktoYourVisitors

"Chatback"isGoogle'snameforalivehelpfeatureforyour

site.Morethanidlechatter,itcanbeanadditionalformof

communicationonyoursite(complementingthingslike

commentforms,oryourAboutpagewithcontactinfolikean

emailaddress).

Otherthanmeasuringyourvisitorsinmerenumbers,or

conductingasurvey[Hack#136],youcanalsodirectlychat

withvisitorstogetfeedback!Googleoffersachatbadgethat

youcanpostontoyourblogoranyotherwebpage,makingthis

asimpleundertaking,atleasttechnically(takingthetimeto

speakwithyourvisitors,andhandlingmultipleconversationsat

once,isadifferentmatter).

Togetthechatwidget,visit

http://google.com/talk/service/badge/Newandcustomizethe

badgebyadjustingthetitleandotheroptions.Yourtitleof

choicemaybe"Talktome,""Havefeedback?I'mlistening,"

"Askmeaquestion,"oranythingelse.Ifyoueditthe

configuration,clickthe"Updatebadge"buttontorefreshthe

snippet.Copythesnippet(seeFigure12-17)andpasteitinto

yourblogsoftware'sHTMLeditingtab,oranyotherhomepage

editorofchoice.(FormorevalidHTML,youmaywanttoescape

theampersandcharactersinthesnippet'sURLbywriting&

insteadofjust&.)



NOTE

Ifyourtitleistoolongforthespeechbubble,helpis

onlyafewcharacterstrokesaway:youcanadjustthe

widthparameterintheURL,aswellastheIFrame's

widthattribute,toexpandthelengthofthebadge's

speechbubble.Thebubble'sheightcanbeadjustedtoo.

Forinstance,youcanchangethesnippetpartthat

readsw=200&h=60tow=400&h=80,andthenchange

width="200"height="60"towidth="400"



height="80".

LogintoGoogleTalk(onewayistoopen

http://talkgadget.google.com/talkgadget/popoutinyour

browser),andthengolivewithyourblogpostorthechanges

youmadetoyourhomepage.Theexactwaythewidget

displaysdependsonyourconfigurationsandyouronlinestatus

—ifyou'vesetyourGoogleTalkstatusto"busy,"oryou're

loggedoutofchat,peoplewon'tbeabletolaunchachatwith

youfromthechatbadge.

Nowwheneveryou'reavailable,visitorscanlaunchachatwith

youbyclickingonthebadge.TheydonotneedaGoogle

Accounttodoso.Andyouwillnotbeabletoidentifythemin

anywayotherthanwhattheymayrevealaboutthem

themselves,astheywillshowas"Guest."Figure12-18,onthe

otherhand,showswhatthechatwilllooklikefromthevisitor's

end.



ThisdialogtakesyouthroughcreatingaGoogleTalk

chatbackbadge;youcanexpandandcollapsethe

advancedoptionsviatheEditlink



WhatthechatlookslikeforoneofthevisitorstoJane's

blog



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Hack 137. Visualize Traffic with DIY Vector Graphics

Tải bản đầy đủ ngay(0 tr)

×