Two.js has a few helpful methods to draw simple shapes like circles, rectangles, lines, and ellipses, but if we want to draw more complex shapes we ...
Coder
steps(6)
Two.jsPuppy
DownloadCompleteProject39k|.zipfile
Description
DrawingwithcodecanbeawalkintheparkwiththehelpofJavascriptandthehandydrawinglibraryTwo.js.Injustafewlinesofcodeyourbrowserbecomesyoursketchbook.
Agreatprojectfor:
Doglovers,doodlers,andjavascriptjunkies.
Medium
SkillsNeeded:
BasicJavascript,BasicHTML,BasicCSS
SkillsLearned:
BasicTwo.js,WorkingwithJavascriptLibraries
SubmittedBy:
CoderTeam
Beforewegetstartedwithtwo.js.
Drawingapuppyseemssimple(anditiswithTwo.js!)butitrequiresalittleexperiencewithJavascriptfirst.Ifyou’veneverventuredintotheJStabonCoderyoumightwanttostartwithapreviousproject.
PreviousCoderProject:Night&Day
ThisprojectwillintroduceyoutoJavascript,theJStabandhowtomakeyourcomputerdosomeofthethinkingforyou.
PreviousCoderProject:Clock
Whattimeisit?You’llfinallybeabletoanswerthatquestionafteryou’vebuiltthissimpleclock.
Download:Two.jsLibrary
Inthisprojectwe’llbeusinga2DdrawinglibraryforJavascript.Youcandownloadthetwo.jsfilehere(rightclickthelinkanddownloadtoyourdesktop).There'salsoatonmoretolearnaboutattheTwo.jswebsite.
Step1:Settingupoursketchbook.
Let’sgetdrawing!We’llneedtodoalittlebitofsetup,butoncewe’vegotthepiecesinplacewe’llbeabletodrawwithjustafewlinesofcode.Firstwe’lluploadtheTwo.jslibrarytoourproject,thenwe’lltellthecodehowtofindTwo.js.We’reactuallyalreadyusingsomeotherhelpfuljavascriptlibraries,likejQuery&Ace,soaddingTwo.jswillbeabreeze.InfactyoucanuseallsortsofhelpfullibrarieswithCoderusingthesesamesteps.
Ifyouhaven’talready,goaheadanddownloadTwo.jsitshouldbeafilecalled:two.js.
StartanewCoderappandcallitwhateveryou’dlike.We’llcallours“TwoPuppy”.
Firstthing’sfirst,let’saddthetwo.jsfiletoourapp.We’lldothatjustlikeanimageoraudiofile.Openthemediatab,hitthe+button,anduploadthetwo.jsfileyoudownloadedearlier.
LookinthetagofyourHTML,you’llseeafewlinesthatpointtoother.jsfileswe’reusing,theylooksomethinglikethis:
Duplicateoneofthoselinesanddeletethesrcpathinsidethequotes.Nowwithyourcursorstillinbetweenthequotes,openthemediafolder,hoverovertwo.js,andselectPastetoCode.
Ourcodelookslikethis.Notethatyourpathmightlookatinybitdifferentifyou'venamedyourprojectdifferently.
Whilewe’reintheHTML,tablet’sdeleteeverythingoutoftheandaddanewwithid“doodle”.We’llusethis
abitlater.
Ourfullcodelookslikethis:
Lastset-upstep!DeleteeverythingintheCSStabandgiveyourbodyanicercolorthanjustplainoldwhite.
OurfullCSScodelookslikethis:
body{
background-color:#FFFAED;
}
Nothingtolookatquiteyet.Butnowit’sontotheJStabwhereallthemagichappens.
Step2:Asimplecircle.
Withtwo.jsandjustafewlinesofcodewecanstartdrawingsimpleshapesanywhereinthebrowserwindow.Here’sthefirstbitofjavascriptwe’lladd(insidethe$(document).ready(function())toourJStabtodrawabluecircle.We’llgothroughitlinebylinebelow.
Ourcodelookslikethis:
$(document).ready(function(){
varelem=document.getElementById('doodle');
vartwo=newTwo({fullscreen:true}).appendTo(elem);
vardot=two.makeCircle(120,120,100);
dot.fill='#52C5DC';
dot.noStroke();
two.update();
});
Nottoocrazy,right?Let’sgothroughlinebylineandseewhateachdoes.
Inthefirstlinewecreateavariablecalledelemandsavethelocationofthe‘doodle’
wemadeinourHTMLtab.
Line2isthebigone,itcreatesanewTwo.jsinstanceandgivesitthevariablenametwo.Youhaveafewoptionsatthispoint,buttheonlythingwe’regoingtoworryaboutisfullscreen:truethistellsTwo.jstomakeyourdrawingareathefullsizeofyourbrowserwindow.The.appendTo(elem)attachesournewTwoinstancetothe“doodle”
.ThisisusefulincasewewanttohavemorethanoneTwo.jsinstanceonapageandjustgoodpractice.
Finally,we’redrawingacircle!Two.jshasabunchofhelpermethodstodrawsimpleshapeslikecircles.two.makeCircle()isoneofthosefunctions.Itneedsthreenumberstowork.Thefirsttwoarexandycoordinatesthatsaywherethecenterpointofthecircleshouldbe,thethirdnumberisthecircle’sradius.Sothislineofcodebasicallysays“Drawacirclenamed‘dot’withthecenter120pixelsoverfromtheleft,120pixelsdownfromthetop,andwitharadiusof100pixels.”
Thenext2linesarejust2ofmanypropertiesofthecirclewecanchange..filllet’sussetacolorforourcircleusingfamiliarHEXcolorsand.noStroke()tellsTwo.jsthatwedon’twanttodrawanoutlinearoundthecircle.
Finally,weneedtotellTwo.jstodraweverything!Wedothisbycallingthetwo.update()function.Forthisprojectwejustneedtohavethatlineattheendofourcode,butinmoreadvancedprojectsthereareotherwaystotellTwo.jstodraw.
Ifyou’vegoteverythingtypedincorrectlyyoushouldseeabluecircleinthetopleftofyourpreviewscreen.TrychangingsomeofthenumbersusedforthecircleorswapinyourfavoriteHEXcolor.
Step3:JustDoodling.
Step2coveredthebasicsofTwo.jsbutbeforewediveintodrawingourpuppylet’splaywith2moredrawfunctionsinTwo.js:makeLine()&makeRectangle().Theydojustwhatyou’dexpect,butrequireslightlydifferentcode.Tryaddingthiscodebeforetwo.update().
Ourcodelookslikethis:
varrect=two.makeRectangle(260,120,210,100);
rect.fill='#6cbf58';
rect.stroke='#ffffff';
rect.linewidth=5;
varline=two.makeLine(20,20,210,300);
line.stroke='#ff4c22';
line.linewidth=8;
Basedonthecircle,youcanprobablyguesswhat’sgoingonhere,butlet’slookatafewofthedetails.
two.makeRectangle()doesexactlythat,youjustneedtogiveitanxandyforthecenterpoint,awidth,andaheight.Sothislinesays“Makearectanglenamed‘rect’260pixelsoverfromtheleft,120pixelsdownfromthebottom,210pixelswide,and100pixelstall.”
Thenweusesomenewpropertiesofrect,.strokeset’sourrectanglesstrokecolorand.linewidthlet’sussayhowmanypixelsthickthestrokeshouldbe.Simple.
two.makeLine()...makesaline!Wejustgiveit2xandypointsanditconnectsthedots.Wecanusethesame.strokeand.linewidthtostyleit.
Youcanprobablyimagineallsortsofcoolthingstodrawwithjusttheseshapes.Goaheadandplayaroundwithsomeofthenumbersorcreatemorecircles,rectangles,andlines.We’llstartfreshinstep4todrawourpuppy.
Step4:PuppyPositioning.
Nowthatweknowhowtodrawbasicshapeswecandrawalmostanything.Whenyoucandrawanything,whynotdrawapuppy?Tohelpusdrawwe’regoingtouseafewmoretricksandvariables,justtomakeitalittlebiteasier.
Also,upuntilnowwehaven’texactlyexplainedthexandynumbersthatdetermineposition,butit’ssimple.Two.jsusesabasiccoordinatesystemwith0,0intheupperleftcornerofyourbrowser,withthenumbersincreasingasyoumovedownandtotheright.XgetsbiggertotheRight,Ygetsbiggertowardthebottom.You’llfindthatalmostallgraphicsprogrammingusesthissamecoordinatesystem.
Sowithallthatinmind,let’swritesomecodetodrawacircleinthemiddleofourscreen,nomatterwhatsizeourbrowseris.
Goaheadanddeleteallthejavascriptyou’vewritten(orevenstartfreshCoderapp)andwritethisinsidethe$(document).ready(function()function.
Ourcodelookslikethis:
varelem=document.getElementById('doodle');
vartwo=newTwo({fullscreen:true}).appendTo(elem);
varposition=newTwo.Vector(two.width/2,two.height/2);
varhead=two.makeCircle(position.x,position.y,100);
head.fill='#52C5DC';
head.noStroke();
two.update();
Wereallyonlyneededonenewlineofcodetocenterthecircleinourscreen.Let’stakealook.
OurthirdlineofcodecreatesanewTwo.jsVectorthatwe’venamedposition.ATwo.Vectorissimplyavariablethatcanhold2numbersinsteadof1,perfectforcoordinates!Youcanaccesseachnumberbyadding.xor.ytothenameofyourvector.
Insteadofassigningstaticnumbersthepositionvectorwe’reusinganotherfeatureofTwo.js:two.widthandtwo.height.Sincewe’vealreadytoldTwo.jstobethefullsizeofourbrowsertheseareeasywaystogetthewidthandheightofthebrowserwindow.Anddividingtwo.widthandtwo.heightby2willgiveusthecenterpointofthebrowsereverytime.
Thelastthingweneedtodoisuseournewpositionvectortodrawacircle.Soinsteadofusingnumbersforthetwo.makeCircle()centerpoint,we’resaying:position.xandposition.y.(Wecan’tjustsayposition,becausethecirclemethodexpects2numbersseparatedbyacomma.)
Previewyourappnowandtryresizingandrefreshingtheapp.Thecirclewon’tmovewhenyouresizethebrowser,justwhenyourefresh,butit’sstillagreatwaytopositionthingswhenyou’renotsurewhatsizethebrowserwindowwillbe.
Step5:PuppyTime.
Oddlyenough,we’realmostdone!Usingeverythingwe’velearnedwecandraw(almost)allofthepiecesofapuppy.Checkouthowwe’redrawingtherestofthepuppyinthecodebelow.Oneimportantthingtonote,you’llneedtodrawyourshapesintheorderyouwantthemlayered.Justlikerealpaint,thefirstthingyoudrawwillbeatthebottom.
Ourcodeafterhead.noStroke();lookslikethis:
varnose;
nose=two.makeCircle(position.x,position.y+30,32);
nose.fill='#EFB8D2';
nose.noStroke();
vareyeLeft;
eyeLeft=two.makeCircle(position.x+42,position.y-26,32);
eyeLeft.fill='#FFFFFF';
eyeLeft.noStroke();
varpupilLeft;
pupilLeft=two.makeCircle(position.x+42,position.y-26,20);
pupilLeft.fill='#7FC35E';
pupilLeft.noStroke();
varearLeft;
earLeft=two.makeEllipse(position.x-100,position.y-80,26,46);
earLeft.fill='#52C5DC';
earLeft.noStroke();
earLeft.rotation=Math.PI/4;
Itlookslikealot,butit’sreallyjustsamebitofcodeweusedtodrawourcirclerepeatedforotherpartsofthepuppy.Thereareafewnewthingsintheretodrawtheearthatwe’llexplainnow.
FindtheearLeftshape.Seehowwe’redrawinganEllipse,usingtwo.makeEllipse()?Thismethodworksexactlyliketwo.makeRectangle(),butwilldrawanovalshapeinstead.Youjustdefinethecenterpoint,width,andheight.Easy.
Wewanttodrawourearellipseatanangleand,ofcourse,Two.jsmakesiteasywithapropertywecanmodify:.rotation.WespecifyrotationinRadians,whichareabitodd,buteasytoworkwith.Wewon’tgetintothedetailsofthemathbutbymultiplyinganddividingπ(3.14159265…)bydifferentnumberswecanchangetherotationofourshape.TogetpiinjavascriptwecanwriteMath.Pi.Trychangingthenumbersinthecodetoseehowtheearrotates.
Westillneedtodrawtherightsideofthepuppy!Trymakingtherighteye,pupil,andearonyourownbasedontheleftside’scode.Ifyou’refeelinglazyourcodeisbelow.
Ourcodelookslikethis:
vareyeRight;
eyeRight=two.makeCircle(position.x-42,position.y-26,32);
eyeRight.fill='#FFFFFF';
eyeRight.noStroke();
varpupilRight;
pupilRight=two.makeCircle(position.x-42,position.y-26,20);
pupilRight.fill='#7FC35E';
pupilRight.noStroke();
varearRight;
earRight=two.makeEllipse(position.x+100,position.y-80,26,46);
earRight.fill='#52C5DC';
earRight.noStroke();
earRight.rotation=-Math.PI/4;
Ourpuppyisalmostcomplete,buthe’smissingamouth!That’samorecomplexshapethatwe’llcoverinourfinalstep.
Step6:LickitySplit.
Two.jshasafewhelpfulmethodstodrawsimpleshapeslikecircles,rectangles,lines,andellipses,butifwewanttodrawmorecomplexshapeswe’llhavetodoitourselves.Ourpuppy’stongueisbasicallyhalfanellipse,butthatmakesitauniqueshapethatwe’lldrawusinganewmethodcalledtwo.makePolygon().Itworksalittlebitlikeatwo.makeLine()butwecanuseasmanypointsaswewant.Checkoutthecodeforourtongue.
Ourcodelookslikethis:
vartongue;
tongue=two.makePolygon(0,0,100,0,100,0,90,58,50,80,10,58,0,0);
tongue.curved=true;
tongue.fill='#EE3E36';
tongue.noStroke();
Ifyoupreviewthiscodeyou’llseethetongueisprettybigandstuckinthetopleftcorner.That’sok,wecanreposition,scale,androtateitlater.Here’swhatthesefirstfewlinesaredoing.
Wepassed7setsofx,ycoordinatesintothemakePolygonmethodtodefinetheshape.Tomakethingseasiertowritewestartedat0,0andthenaddedpointsintheorderwewantedthemtoconnect
tongue.curvedisanewpropertythatwesettotruetotellTwo.jstomaketheconnectionsbetweenthepointscurved.Thisissowehavearoundedtongue.Youcantrychangingittofalseandseewhathappens.
Youmightnoticewedoubledupthepoints(100,0)and(0,0).Thisisalittlehacktomakethetopleftandtoprightofthetonguehaveahardangleinsteadofaroundedcorner.WhenTwo.jstriestomakeacurvededgebetweentwopointsthatareintheexactsamelocationwegetacorner.
Thelastfewlinesshouldlookfamiliartoyou,justbasicstylingofthetongue.
Nowlet’sgetthetongueintherightplace.Here’safewmorelinesofcodewithsomenewpropertiesthathelpuspositionthetongue.
Ourcodelookslikethis:
tongue.translation.x=position.x-40;
tongue.translation.y=position.y+86;
tongue.scale=0.4;
tongue.rotation=Math.PI/5;
Thefirst2linesusetheproperty.translationtoshiftthetonguedownandleftonthescreen.Wehavetospecifyifwe’reshiftingonthexoryaxisbyaddinga.xor.yto.translation.Also,noticewe’reusingourpositionvariabletoeasilyfindthecenterofthescreen.
Thenextnewpropertyis.scale.Itworkswithdecimalnumbers,1isequalto100%,so0.4is40%.
Onelastlinetorotatethetongueandwe’redone!
That’sit!Previewyourapp,andifeverythingiswrittencorrectlyyoushouldseeyournewpuppy.
BonusRounds
Nowthatwe’vegotthebasicsofdrawingdone,let’sseewhatelsewecanmakewithTwo.js.
It’saZoooutthereMedium
Dogs,cats,andsnakes?!Withthesametechniquesweusedtodrawapuppyseeifyoucancreateothercrazycritters.
ExploreTwo.jsHard
YoucandoalotmorethansimpledrawingswithTwo.js.HeadovertotheTwo.jswebsitetolearnmoreaboutdrawing,animation,andinteractivity.
CoderProjectstoTryNext
Likedrawingwithcode?There’smorethanonewaytogetpixelsonthepage.Trytheseothercoderprojectstomakemorecoolthingsandlearnmoreusefulstuff.
MakeYourOwnMondrian
Paintmakesamess.Codeissomuchcleaner.UsethisprojecttorecreateaclassicModernartwork,PietMondrian’sCompositionIIinRed,Blue,andYellowinyourbrowserwithCSSandHTML.
OpenProject
Easy
MusicBoxes
Let’sturnitup.Thisprojectwilltransformyourbrowserintoasimpleinstrumentthatyoucanusetomakemusic.
OpenProject
Medium