A Beginner's Guide to Drawing 2D Graphics With Two.js - Code
文章推薦指數: 80 %
Two.js an API that makes it easy to create 2D shapes with code. Follow along and you'll learn how to create and animate shapes from ...
Unlimited
Plugins,WordPressthemes,videos&courses!
Unlimitedassetdownloads!
From$16.50/m
DismissSignInHow-ToTutorialsDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGameDevelopmentComputerSkillsCoursesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGuidesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGameDevelopmentComputerSkillsEnvatoElementsEnvatoStudioCommunityHelpEnvatoElementsEnvatoStudioCommunityForumHelpSignInHow-ToTutorialsDesign&IllustrationAdobePhotoshopAdobeIllustratorDrawingAdobeInDesignPhotoManipulationGraphicDesignTextEffectsVectorPhotoshopActionsIconDesignMoreCategories...LearningGuidesCodeJavaScriptWordPressMobileDevelopmentPHPLaravelCMSSwiftAndroidSDKReactAngular2+MoreCategories...LearningGuidesWebDesignCSSHTML&CSSAnimationUIDesignAdobePhotoshopSketchWorkflowDesignTheoryJavaScriptUXMoreCategories...LearningGuidesPhoto&VideoPhotographyVideoEditingHow-ToInspirationLightingAdobePhotoshopAdobeAfterEffectsAdobePremiereProAdobeLightroomMoreCategories...LearningGuidesBusinessSmallBusinessEntrepreneurshipFreelanceCareersMarketingFinanceProductivityPlanningCommunicationHow-ToMoreCategories...LearningGuidesMusic&AudioAudioProductionLogicProGeneralMixing&MasteringSoundDesignWorkshopsReasonRecordingAbletonLiveCubaseMoreCategories...LearningGuides3D&MotionGraphicsAdobeAfterEffects3D3DStudioMaxMotionGraphicsMayaCinema4DWorkflowBlenderVisualEffectsRoundupsMoreCategories...LearningGuidesGameDevelopmentGameDesignPlatformAgnosticGameMechanicsBusinessProgrammingGameArtLevelDesignFromScratchUnityHTML5MoreCategories...LearningGuidesComputerSkillsOSXAppTrainingProductivityHow-ToTips&ShortcutsCustomizationAutomationSecurityHardwareMicrosoftPowerpointMoreCategories...LearningGuidesCoursesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGuidesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGameDevelopmentComputerSkillsAdvertisementCodeJavaScriptABeginner'sGuidetoDrawing2DGraphicsWithTwo.jsAdvertisementAdvertisementAdvertisementAdvertisementAdvertisementbyMontyShokeenAug24,2018ReadTime:11minsLanguages:EnglishDeutschEspañolBahasaIndonesiaPусскийJavaScriptGraphicsSVGCanvasFront-End
Two.jsanAPIthatmakesiteasytocreate2Dshapeswithcode.Followalongandyou'lllearnhowtocreateandanimateshapesfromJavaScript.
Two.jsisrendereragnostic,soyoucanrelyonthesameAPItodrawwithCanvas,SVG,orWebGL.Thelibraryhasalotofmethodswhichcanbeusedtocontrolhowdifferentshapesappearonthescreenorhowtheyareanimated.
Installation
Theuncompressedversionofthelibraryhasasizeofaround128KB,whilethecompressedversionis50KB.Ifyouareusingthelatestversion,youcanfurtherreducethesizeofthelibraryusingacustombuild.
YoucaneitherdownloadtheminifiedversionofthelibraryfromGitHuboryoucanlinkdirectlytotheCDNhostedversion.Onceyouhaveaddedthelibrarytoyourwebpage,youcanstartdrawingandanimatingdifferentshapesorobjects.
CreatingBasicShapes
First,youneedtotellTwo.jsabouttheelementonwhichyouwanttodrawandanimateyourshapes.YoucanpasssomeparameterstotheTwoconstructortosetthingsup.
Setthetypeofrendererusingthetypeproperty.Youcanspecifyavaluelikesvg,webgl,canvas,etc.Thetypeissettosvgbydefault.Thewidthandheightofthedrawingspacecanbespecifiedusingthewidthandheightparameters.Youcanalsosetthedrawingspacetothefullavailablescreenusingthefullscreenparameter.Whenfullscreenissettotrue,thevaluesofwidthandheightwillbedisregarded.
Finally,youcantellTwo.jstoautomaticallystartananimationwiththehelpoftheBooleanautostartparameter.
Afterpassingallthedesiredparameterstotheconstructor,youcanstartdrawinglines,rectangles,circles,andellipses.
Youcandrawalineusingtwo.makeLine(x1,y1,x2,y2).Here,(x1,y1)arethecoordinatesofthefirstendpoint,and(x2,y2)arethecoordinatesofthesecondendpoint.ThisfunctionwillreturnaTwo.Lineobject,whichcanbestoredinavariableforfurthermanipulationatalaterpoint.
Inasimilarmanner,youcandrawnormalandroundedrectanglesusingtwo.makeRectangle(x,y,width,height)andtwo.makeRoundedRectangle(x,y,width,height,radius)respectively.Rememberthatxandydeterminethecenteroftherectangle,insteadofitstopleftcoordinateslikemanyotherlibraries.Thewidthandheightparameterswilldeterminethesizeoftherectangle.Theradiusparameterisusedtospecifythevalueoftheradiusfortheroundedcorner.
Youcanalsorendercirclesandellipsesonawebpageusingtwo.makeCircle(x,y,radius)andtwo.makeEllipse(x,y,width,height)respectively.Justliketherectangles,thexandyparametersspecifythecenterofthecircleorellipse.Settingthewidthandheighttothesamevalueinthecaseofanellipsewillrenderitlikeacircle.
OneusefulmethodinTwo.jsthatyouwillusefrequentlyistwo.makeGroup(objects).Youcaneitherpassalistofdifferentobjectsorpassanarrayofobjects,pathsorgroupsastheparametertothismethod.ItwillalsoreturnaTwo.Groupobject.
ManipulatingObjectsinaGroup
Afteryouhavecreatedagroup,youcanmanipulateallitschildrenatonceusingpropertiesthatthegroupmakesavailabletoyou.
Thestrokeandfillpropertiescanbeusedtosetthestrokeandfillcolorforallchildreninagroup.TheywillacceptallvalidformsinwhichyoucanrepresentacolorinCSS.ThismeansthatyouarefreetouseRGB,HSL,orhexnotation.Youcanalsosimplyusethenameofthecolor,like orange,red,or blue.Similarly,youcansetvaluesforallotherpropertieslikelinewidth,opacity,miter,andcap.ItispossibletoremovethefillandstrokefromallchildreninagroupusingthenoFill()andnoStroke()methods.
Youcanalsoapplyotherphysicaltransformationslikescale,rotation,andtranslation.Thesetransformationswillbeappliedonindividualobjects.Addingnewobjectstoagroupandremovingthemiseasywithmethodslikeadd()andremove().
DefiningGradientsandWritingText
YoucandefinebothlinearandradialgradientsinTwo.js.Definingagradientdoesnotmeanthatitwillberenderedautomaticallyonthescreen,butitwillbeavailableforyoutousewhensettingthefillorstrokevaluesofvariousobjects.
Youcandefinealineargradientusingtwo.makeLinearGradient(x1,y1,x2,y2,stops).Thevaluesx1andy1 determinethecoordinatesofthestartofthegradient.Similarly,thevaluesx2andy2 determinethecoordinatesoftheendofthegradient.ThestopsparameterisanarrayofTwo.Stopinstances.Thesedefinethecolorsofeachpartofthearrayandwhereeachcolortransitionsintothenext.Theycanbedefinedusing newTwo.Stop(offset,color,opacity),whereoffsetdeterminesthepointonthegradientwherethatparticularcolorhastobefullyrendered.Thecolorparameterdeterminesthecolorofthegradientattheparticularpoint.YoucanuseanyvalidCSScolorrepresentationsasitsvalue.Finally,theopacityparameterdeterminestheopacityofthecolor.Theopacityisoptional,anditcanhaveanyvaluebetween0and1.
Youcandefineradialgradientsinasimilarmannerusingtwo.makeRadialGradient(x,y,radius,stops,fx,fy).Inthiscase,thevaluesxandydeterminethecenterofthegradient.Theradiusparameterspecifieshowfarthegradientshouldextend.Youcanalsopassanarrayofstopstothismethodinordertosetthecolorcompositionofthegradients.Theparametersfxandfyareoptional,andtheycanbeusedtospecifythefocalpositionforthegradient.
CheckoutsomeofthetypesofgradientandtheircodeintheCodePenbelow.
Rememberthatthexandypositionofthegradientsarewithrespecttotheoriginoftheshapetheyaretryingtofill.Forinstance,aradialgradientwhichissupposedtofillashapefromthecenterwillalwayshavexandysettozero.
Two.jsalsoallowsyoutowritetextonthedrawingareaandupdateitlateraccordingtoyourneeds.Thisrequirestheuseofthemethodtwo.makeText(message,x,y,styles).Itmightbeevidentfromthenameoftheparametersthatmessageistheactualtextthatyouwanttowrite.Theparametersxandyarethecoordinatesofthepointwhichwillactasthecenterforwritingthetext.Thestylesparameterisanobjectwhichcanbeusedtosetthevaluesofalargesetofproperties.
Youcanusestylestosetthevaluesofpropertieslikefontfamily,size,andalignment.Youcanalsospecifythevalueofpropertieslikefill,stroke,opacity,rotation,scale,andtranslation.
CreatingaTwo.jsProject
Afterlearningaboutallthesemethodsandproperties,itistimetoapplythemtoaproject.Inthistutorial,IwillshowyouhowwecanuseTwo.jstorenderthefirsttenelementsoftheperiodictablewithelectronsrotatingaroundthenucleus.Thenucleuswillalsohavesomeslightmovementtoimprovethevisualappealofourrepresentation.
Webeginbydefiningsomevariablesandfunctionswhichwillbeusedlater.
varcenterX=window.innerWidth/2;
varcenterY=window.innerHeight/2;
varelem=document.getElementById("atoms");
varelementNames=[
"",
"Hydrogen",
"Helium",
"Lithium",
"Beryllium",
"Boron",
"Carbon",
"Nitrogen",
"Oxygen",
"Fluorine",
"Neon"
];
varstyles={
alignment:"center",
size:36,
family:"Lato"
};
varnucleusCount=10;
varnucleusArray=Array();
varelectronCount=10;
varelectronArray=Array();
functionintRange(min,max){
returnMath.random()*(max-min)+min;
}
TheabovecodestoresthecoordinatesofthecenterofourwindowinthevariablescenterXandcenterY.Thesewillbeusedlatertoplaceouratominthecenter.The elementNames arraycontainsthenamesofthefirsttenelementsoftheperiodictable.Theindexofeachnamecorrespondstothenumberofelectronsandprotonsofthatelement,and itbeginswithanemptystring.Thestylesobjectcontainspropertiesforstylingthetextobject.
WehavealsodefinedafunctionintRange()togetarandomintegervaluewithingivenextremes.
vartwo=newTwo({fullscreen:true}).appendTo(elem);
varprotonColor=two.makeRadialGradient(
0,
0,
15,
newTwo.Stop(0,"red",1),
newTwo.Stop(1,"black",1)
);
varneutronColor=two.makeRadialGradient(
0,
0,
15,
newTwo.Stop(0,"blue",1),
newTwo.Stop(1,"black",1)
);
for(i=0;i
延伸文章資訊
- 1two.js之實現動畫效果示例 - 程式前沿
一、什麼是two.js? Two.js 是面向現代Web 瀏覽器的一個二維繪圖API。Two.js 可以用於多個場合:SVG,Canvas 和WebGL,旨在使平面形狀和動畫的建立更 ...
- 2jonobr1/two.js: A renderer agnostic two-dimensional ... - GitHub
Two.js ... A two-dimensional drawing api meant for modern browsers. It is renderer agnostic enabl...
- 3Two.js Puppy | Coder Projects - GitHub Pages
Two.js has a few helpful methods to draw simple shapes like circles, rectangles, lines, and ellip...
- 4two.js - Libraries - cdnjs - The #1 free and open source CDN ...
A two-dimensional drawing api meant for modern browsers. - Simple. Fast. Reliable. Content delive...
- 5A Beginner's Guide to Drawing 2D Graphics With Two.js - Code
Two.js an API that makes it easy to create 2D shapes with code. Follow along and you'll learn how...