how to code a drawing canvas
In this tutorial we will create a simple drawing app in the browser. To practise that we volition use vanilla JS and the Canvas API.
Afterward this tutorial yous'll have a neat overview of the canvas API and consequence handling in javascript.
Video tutorial
If you would watch a detailed step-by-step video instead you can bank check out the video I made covering this project on my Youtube Channel:
HTML markup
Nosotros'll commencement past wrapping the whole app into a section
with the class of container
. This volition be used to align the toolbar and the cartoon board.
Inside that nosotros create a div
which will concord our toolbar. I as well set an id of toolbar
for it and then information technology will be easier to work with information technology in javascript.
Within the toolbar nosotros'll add together a title for our app in an h1
. Below that nosotros'll add 2 input fields: 1 for color and 1 for the with of the line. For the color input I add together the id of stroke
equally it will define the color of the stroke and for the number input I'll add the id of lineWidth
. Don't forget to add together the corresponding labels for these input fields. Lastly I'll add a button with the id of clear
and this will be used to clear the drawing board.
The side by side thing we have to add together in our html is the actual drawing board. Information technology will be a canvas
chemical element, but for layouting purposes we'll wrap it into a div
.
Lastly we need to add the script tag for our script at the bottom of the body
.
<section class= "container" > <div id= "toolbar" > <h1>Describe.</h1> <label for= "stroke" >Stroke</label> <input id= "stroke" name= 'stroke' type= "colour" > <label for= "lineWidth" >Line Width</label> <input id= "lineWidth" proper noun= 'lineWidth' type= "number" value= "v" > <button id= "clear" >Clear</button> </div> <div> <canvas id= "drawing-board" ></sail> </div> </section> <script src= "./index.js" ></script>
Add styles with CSS
I'll start past removing any browser defined paddings and margins. Also set up the height of the body to 100% and remove the scrollbar with overflow: hidden.
body { margin : 0 ; padding : 0 ; meridian : 100% ; overflow : hidden ; color : white ; }
For the championship I'll add together a gradient text colour.
h1 { background : #7F7FD5 ; groundwork : -webkit-linear-gradient ( to correct , #91EAE4 , #86A8E7 , #7F7FD5 ); background : linear-gradient ( to correct , #91EAE4 , #86A8E7 , #7F7FD5 ); background-clip : text ; -webkit-background-clip : text ; -webkit-text-fill-color : transparent ; }
We'll also make the container 100% height, set the display to flex.
.container { height : 100% ; brandish : flex ; }
For the toolbar we will use flexbox with column direction. The width of the toolbar volition have a fixed width of 70px. We'll add together some spacing with 5px of padding and set up a dark groundwork for it.
For the toolbar elements I use some basic styling. Feel complimentary to copy these styles 👇
#toolbar { display : flex ; flex-direction : column ; padding : 5px ; width : 70px ; background-color : #202020 ; } #toolbar * { margin-bottom : 6px ; } #toolbar label { font-size : 12px ; } #toolbar input { width : 100% ; } #toolbar button { background-color : #1565c0 ; border : none ; edge-radius : 4px ; colour : white ; padding : 2px ; }
Implementing the javascript part.
First nosotros'll salve references for the toolbar and the drawing board (canvas).
const canvas = document . getElementById ( ' drawing-board ' ); const toolbar = document . getElementById ( ' toolbar ' );
Next we have to go the context of the canvas. We'll use this context to describe on the sail. We tin can do that by calling the getContext
method of the sail. We'll draw in 2d so we accept to provide that equally a parameter.
const ctx = canvas . getContext ( ' 2d ' );
In the next stride nosotros'll assemble the offsets (altitude between the canvas edges to the edge of the viewport) and save them. In this case the top offset will exist 0px as the sheet takes the full height of the viewport and the left get-go will be 70px as we accept a fixed width sidebar on the left. Adjacent we will calculate and set the acme and the width of the canvas by subtracting the offsets from the viewport's width and height.
const canvasOffsetX = canvas . offsetLeft ; const canvasOffsetY = canvas . offsetTop ; canvas . width = window . innerWidth - canvasOffsetX ; canvas . tiptop = window . innerHeight - canvasOffsetY ;
Now we will set some global variables. The isPainting
variable will reflect whether we are currently drawing or not. We'll fix a basic line width of v px. Lastly we'll declare 2 variables (startX & startY) which volition concur the coordinates of the bespeak which we started the drawing from.
let isPainting = simulated ; let lineWidth = 5 ; let startX ; let startY ;
Let'due south offset to add event listeners at present. First we volition add together a click event listener to the toolbar. If the due east.target.id
is articulate (and then the articulate button was clicked) then we'll call the clearRect
function and provide it the width and height of the canvas. What this method will do is esentially set every pixel of the canvas to white within the provided width and height values (so in this case the whole canvas).
toolbar . addEventListener ( ' click ' , e => { if ( e . target . id === ' clear ' ) { ctx . clearRect ( 0 , 0 , canvass . width , canvas . tiptop ); } });
Next we will handle the input changes for the line width and the cartoon color. We'll employ event delegation in this case. So instead of defining separate event handlers for each input field, nosotros'll add only i effect listener to the parent element and handle the events from there. We can differentiate which input field was changed past checking the value of eastward.target
. If the color was changed we'll ready the strokeStyle
of the canvas context, if the lineWidth was changed then we update the value of the global lineWidth
variable with the new value.
toolbar . addEventListener ( ' change ' , e => { if ( e . target . id === ' stroke ' ) { ctx . strokeStyle = east . target . value ; } if ( e . target . id === ' lineWidth ' ) { lineWidth = east . target . value ; } });
Next nosotros'll implement the drawing controls. When the mousedown event happens (the user clicks and holds the mouse button down) we'll set the isPainting
variable to true and set the current mouse position's coordinates into startX
and startY
.
If the user releases the mouse push button, then we'll set isPainting
to fake and phone call the stroke
method of the context to colorize the already drawn path. Nosotros besides have to call the beginPath
method to close the path that the user drawn then far. Nosotros have to practice this because if the user wants to draw another line it would start from this position, and this is not something that we desire.
Lastly we'll add an event listener to the mousemove event. When the user moves the mouse we'll call the describe function which we'll implement next.
canvass . addEventListener ( ' mousedown ' , ( e ) => { isPainting = true ; startX = e . clientX ; startY = e . clientY ; }); canvas . addEventListener ( ' mouseup ' , e => { isPainting = false ; ctx . stroke (); ctx . beginPath (); }); canvas . addEventListener ( ' mousemove ' , draw );
In the draw
function we'll outset check the value of the isPainting
variable if it is false we are not drawing then we'll just simply telephone call return.
Next we'll set up the line width to accept the value from the global variable and set the lineCap to circular. After this we'll draw a line past calling the lineTo
method with the electric current mouse position's coordinates. One thing you have to be careful is to decrease the offset from the X coordinate because otherwise the drawn line would be offsetted with the width of the sidebar (70px). Lastly we just take to telephone call the stroke
method to give the line the colour that nosotros selected.
const draw = ( e ) => { if ( ! isPainting ) { render ; } ctx . lineWidth = lineWidth ; ctx . lineCap = ' circular ' ; ctx . lineTo ( e . clientX - canvasOffsetX , e . clientY ); ctx . stroke (); }
And this is it now you have a working drawing app!
If you stuck at any signal you tin can picket the video or you can take a look at the source lawmaking on Codepen.
Where tin you lot acquire more from me?
I create education content roofing web-development on several platforms, feel free to 👀 check them out.
I also create a newsletter where I share the week'southward or ii week'south educational content that I created. No bull💩 merely educational content.
🔗 Links:
- 🍺 Support gratuitous education and buy me a beer
- 💬 Join our community on Discord
- 📧 Newsletter Subscribe here
- 🎥 YouTube Javascript Academy
- 🐦 Twitter: @dev_adamnagy
- 📷 Instagram @javascriptacademy
Source: https://dev.to/javascriptacademy/create-a-drawing-app-using-javascript-and-canvas-2an1
Posted by: fleckthervin.blogspot.com
0 Response to "how to code a drawing canvas"
Post a Comment