A Beginner's Guide to Drawing 2D Graphics With Two.js - Code

文章推薦指數: 80 %
投票人數:10人

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=2&&i<10){ varshellRadius=80; varangle=(i-2)*Math.PI/4; electronArray.push( two.makeCircle( Math.cos(angle)*shellRadius, Math.sin(angle)*shellRadius, 5 ) ); } } Placingneutronsandprotonsinsidethenucleuswaseasy.However,properlyplacingtheelectronsatauniformdistancewillrequirealittlemaths.WeusetheshellRadiusvariabletospecifythedistanceofdifferentelectronshellsfromthenucleus.Awholecirclecoversanangleequalto2PIradians.Wecanplacedifferentelectronsuniformlybydistributingthe2PIradiansbetweenthemequally. TheMath.cos()andMath.sin()functionsareusedtoseparatetheverticalandhorizontalcomponentsofthepositionvectorofdifferentelectronsbasedontheirangle. varorbitA=two.makeCircle(centerX,centerY,50); orbitA.fill="transparent"; orbitA.linewidth=2; orbitA.stroke="rgba(0,0,0,0.1)"; varorbitB=two.makeCircle(centerX,centerY,80); orbitB.fill="transparent"; orbitB.linewidth=2; orbitB.stroke="rgba(0,0,0,0.1)"; vargroupElectronA=two.makeGroup(electronArray.slice(0,2)); groupElectronA.translation.set(centerX,centerY); groupElectronA.fill="orange"; groupElectronA.linewidth=1; vargroupElectronB=two.makeGroup(electronArray.slice(2,10)); groupElectronB.translation.set(centerX,centerY); groupElectronB.fill="yellow"; groupElectronB.linewidth=1; vargroupNucleus=two.makeGroup(nucleusArray); groupNucleus.translation.set(centerX,centerY); Thispartofthecodeputselectronsfromdifferentshellsaswellasneutronsandprotonsintheirownseparategroups.Italsosetsthefillcolorsforallelectronsinaspecificorbitatonce. two .bind("update",function(frameCount){ groupElectronA.rotation+=0.025*Math.PI; groupElectronB.rotation+=0.005*Math.PI; groupNucleus.rotation-=0.05; }) .play(); vartext=two.makeText("",centerX,100,styles); nucleusArray.forEach(function(nucleus,index){ nucleus.opacity=0; }); electronArray.forEach(function(electron,index){ electron.opacity=0; }); Thispartofthecodesetstheopacityofindividualelectronsandprotonstozero.ItalsotellsTwo.jstorotatetheelectronsandprotonsatspecificspeeds. visible=0; document.addEventListener("click",function(event){ if(visibleel.opacity=0); electronArray.forEach(el=>el.opacity=0); visible=0; text.value=elementNames[0]; } }); Thefinalpartofthecodeallowsustoiteratethroughtheelementsbyclickingthemouseortapping.Toloadthenextelement,wemakeonemoreelectronandonemoreprotonorneutronvisibleandupdatetheelementname.Afterclickingonthelastelement,alltheparticlesarehiddenagainsowecanstartover.Thevisiblevariablekeepstrackofthenumberofatomicparticlesthatarecurrentlyvisiblesothatwecanshoworhidethemaccordingly. TryclickingortappinginthefollowingCodePendemotoseethefirsttenelementsoftheperiodictable. FinalThoughts WebeganthistutorialwithabriefintroductiontotheTwo.jslibraryandhowitcanbeusedtodrawshapeslikerectangles,circles,andellipses.Afterthat,wediscussedhowwecangroupdifferentobjectstogethertomanipulatethemallatonce.Weusedthisabilitytogroupelementstotranslateandrotatetheminsynchronization.Thesetoolsallcametogetherinouranimationoftheatomsofthefirsttenelementsintheperiodictable. Asyoucansee,creatinganimated2DgraphicsisveryeasyusingTwo.js.Thefocusofthispostwastohelpyougetstartedquickly,soweonlycoveredthebasics.However,youshouldreadtheofficialdocumentationtolearnmoreaboutthelibrary! AdvertisementJavaScriptGraphicsSVGCanvasFront-End Didyoufindthispostuseful? Yes No MontyShokeenFreelancer,IndiaIamafull-stackdeveloperwhoalsolovestowritetutorials.Aftertryingoutabunchofthingstillsecondyearofcollege,Idecidedtoworkonmywebdevelopmentskills.StartingwithjustHTMLandCSS,IkeptmovingforwardandgainedexperienceinPHP,JavaScriptandPython. Iusuallyspendmyfreetimeeitherworkingonsomesideprojectsortravelingaround.FeedLikeFollowWeeklyemailsummarySubscribebelowandwe’llsendyouaweeklyemailsummaryofallnewCodetutorials.Nevermissoutonlearningaboutthenextbigthing.UpdatemeweeklyAdvertisementAdvertisementAdvertisement Lookingforsomethingtohelpkickstartyournextproject? EnvatoMarkethasarangeofitemsforsaletohelpgetyoustarted. WordPressPluginsFrom$5PHPScriptsFrom$5JavaScriptFrom$3MobileAppTemplatesFrom$5 UnlimitedDownloadsFrom$16.50/monthGetaccesstooveronemillioncreativeassetsonEnvatoElements.Over9MillionDigitalAssetsEverythingyouneedforyournextcreativeproject.CreateBeautifulLogos,Designs&MockupsinSecondsDesignlikeaprofessionalwithoutPhotoshop.JointheCommunityShareideas.Hostmeetups.Leaddiscussions.Collaborate.QuickLinksExplorepopularcategoriesCuratedDesignAssetsBestCoolFontsInDesignMagazineTemplatesPhotoshopActionsInDesignNewsletterTemplatesInDesignTemplatesCuratedWebDesignAssetsResponsiveWordPressThemesWordPressThemesforConsultantsWireframeTemplatesBestShopifyThemesMasonryWordPressThemesWebThemes&TemplatesWPThemesHTMLTemplatesShopifyThemesBootstrapThemesFreeWordPressThemesVideoAfterEffectsTemplatesAppleMotionTemplatesVideoEffectsLowerThirdsStockFootagePlaceitLogoMakerVideoMakerDesignTemplatesFreeTemplatesMockupsCuratedVideoAssetsAfterEffectsSlideshowTemplatesPremiereProVideoIntroTemplatesFinalCutProTemplatesFinalCutProTitleTemplatesPremiereProVideoEffectsCuratedPresentationAssetsKeynotePitchDeckTemplatesGoogleSlidesBusinessTemplatesPowerPointPitchDeckTemplatesBestShopifyMobileThemesBestPresentationTemplatesFreeToolsImageResizerVideoCropperVideoToGifConverterElementsWordPressThemesStockImagesWebsiteTemplatesLogosFontsTuts+LearnJavaScriptPhotoshopTutorialsHowtoDrawHowtoUseWordPressHowtoUsePowerPoint



請為這篇文章評分?