How to Draw a Line in JavaScript

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

Steps for drawing a line in JavaScript · First, create a new line by calling the beginPath() method. · Second, move the drawing cursor to the point (x,y) without ... SkiptocontentHome»WebAPI»HowtoDrawaLineinJavaScriptSummary:inthistutorial,you’lllearnhowtodrawalineusingtheCanvasAPI.StepsfordrawingalineinJavaScriptTodrawalineonacanvas,youusethefollowingsteps:First,createanewlinebycallingthebeginPath()method.Second,movethedrawingcursortothepoint(x,y)withoutdrawingalinebycallingthemoveTo(x,y).Finally,drawalinefromthepreviouspointtothepoint(x,y)bycallingthelineTo(x,y)method.SetthelinestrokeIfyouwanttostrokethelinewiththestrokeStyle,youcancallthestroke()methodaftercallingthelineTo(x,y)method.SetthelinewidthTosetthewidthforaline,youusethelineWidthpropertyofthe2Ddrawingcontextbeforecallingstroke()method:ctx.lineWidth=10;ThelineTo(x,y)methodThelineTo(x,y)methodacceptsbothpositiveandnegativearguments.Ifthe xispositive,thelineTo(x,y)methoddrawsthelinefromthestartingpointtotheright.Otherwise,itdrawsthelinefromthestartingpointtotheleft.Ifthe yispositive,thelineTo(x,y)methoddrawsthelinefromthestartingpointdownthey-axis.Otherwise,itdrawsthelinefromthestartingpointuptothey-axis.DrawingalineexampleThefollowingshowstheindex.htmlfilethatcontainsacanvaselement: JavaScript-DrawingaLine

JavaScript-DrawingaLine

Codelanguage:HTML,XML(xml)Andthisapp.jscontainsthatdrawsalinewiththecolorred,5-pixelwidthfromthepoint(100,100)to(300,100):functiondraw(){ constcanvas=document.querySelector('#canvas'); if(!canvas.getContext){ return; } constctx=canvas.getContext('2d'); //setlinestrokeandlinewidth ctx.strokeStyle='red'; ctx.lineWidth=5; //drawaredline ctx.beginPath(); ctx.moveTo(100,100); ctx.lineTo(300,100); ctx.stroke(); } draw();Codelanguage:JavaScript(javascript)Thefollowingshowstheoutput:Hereisthelinkthatshowsthecanvaswiththeline.DeveloparesuabledrawLine()functionThefollowingdrawLine()functiondrawsalinefromonepointtoanotherwithaspecifiedstrokeandwidth:functiondrawLine(ctx,begin,end,stroke='black',width=1){ if(stroke){ ctx.strokeStyle=stroke; } if(width){ ctx.lineWidth=width; } ctx.beginPath(); ctx.moveTo(...begin); ctx.lineTo(...end); ctx.stroke(); } Codelanguage:JavaScript(javascript)Todrawalinefrom(100,100)to(100,300)withthelinecolorgreenandlinewidth5pixels,youcancallthedrawLine()functionasfollows:constcanvas=document.querySelector('#canvas'); if(canvas.getContext){ constctx=canvas.getContext('2d'); drawLine(ctx,[100,100],[100,300],'green',5); } Codelanguage:JavaScript(javascript)SummaryUsebeginPath(),moveTo(x,y)andlineTo(x,y)todrawaline.UsethestrokeStyleandlineWidthtosetthelinestrokeandlinewidth.PreviouslyJavaScriptScaleUpNextJavaScriptHistorypushStateSearchfor:GettingStartedJavaScriptFundamentalsJavaScriptOperatorsControlFlowJavaScriptFunctionsJavaScriptObjectsClassesAdvancedFunctionsPromises&Async/AwaitJavaScriptModulesJavascriptErrorHandlingJavaScriptRuntime



請為這篇文章評分?