How To Draw On A Canvas
Read Time: 21 mins Languages:
Combining HTML with the all new <canvas> feature, you can make some pretty crawly web apps! In this tutorial, we will create a great interactive cartoon application using HTML and JavaScript. Along the way, nosotros'll also learn the basic concepts of the all new <canvass> feature.
The <sheet> tag is a relatively new element which is quickly gaining in popularity. It can be used for a diverseness of different things, such as drawing graphs, shapes, images, applying styles and colors, making photo compositions, and even some simple, cracking animations. Today, we'll build a simple online cartoon awarding, similar to http://www.mugtug.com/sketchpad/
Creating a canvas in your site is equally simple as adding the <canvas> tag to your HTML document, as shown below:
<canvas id="canvass" width="800" height="600"> We're deplorable, the browser yous are using does non support <sail>. Please upgrade your browser. <!--Anything inside of the canvas tag volition only display if the browser does not support the <canvas> tag.--> </canvas>
The element 'ID' is not required, just is highly recommended so that y'all can find information technology later in your JavaScript and/or CSS.
Step one What We're Making
Below is an image of what nosotros volition be making. Yours may look a chip different when nosotros are completely finished, depending on the type of styles you lot wish to use, etc.
Equally you can see, I am a terrible drawer, merely maybe after y'all are done creating your chalkboard, you can create an awesome masterpiece! Besides, we're building the chalboard, not the drawing!
Step 2 What Y'all'll Need
You'll need a bones understanding of HTML and JavaScript for this tutorial.
- Photoshop or another image editor
- Code editor of your choice
- Bones cognition of HTML and JavaScript
- <canvass> supported browser (Chrome, Firefox, Opera, Safari)
I volition too be using the free Fugue Icon Pack that can exist downloaded hither: http://p.yusukekamiyamane.com/
Furthermore, we will exist using the following scripts to accomplish the final outcome.
- jQuery 1.4.two Library
- jQuery Tipsy Tooltips
- Base64 and Canvas2Image Library
Pace iii Getting Started
Without further ado, allow's bound right in!
The HTML Markup
Begin by opening your coding application, and create a regular HTML certificate. Copy and paste the lawmaking below. This is the basic construction of our drawing awarding. Save the document in a new folder, labeled canvas (or anything you adopt). Now in the same level as your HTML file, create three new folders.
- JS
- CSS
- Images
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML one.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://world wide web.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-eight" /> <!-- External CSS Document(s) --> <link rel="stylesheet" blazon="text/css" href="css/styles.css" /> <title>Online Drawing Application | Web Blueprint Palatial</championship> <!-- Eternal JavaScript Document(s) --> <script blazon="text/javascript" src="js/canvas.js"></script> </caput> <body> <!-- Wrapper Begins --> <div id="wrapper"> <div id="blackboardPlaceholder"> </div> </div> </trunk> </html>
This is the basic markup of our page. Earlier we brainstorm writing the actual code, let's mode this upwardly a bit. I volition not be showing yous how to brand the design in Photoshop, just you tin can download the images here. Be sure to copy all of the images into the images folder that you just created.
The CSS Markup
Create a new stylesheet named "styles.css," and save it in your "css" folder. Re-create and paste the post-obit bones CSS code beneath to your stylesheet.
@charset "UTF-8"; /* CSS Document */ * { margin:0; padding:0; } torso { background:url(../images/bg.gif) repeat-10 #f8f8f8; color:#d7d7d7; font-family:"Belle","Comic Sans MS", cursive; font-size:25px; line-height:27px;} #wrapper { position:relative; width:960px; margin:0 auto; padding-pinnacle:75px;} <!-- Blackboard --> #blackboardPlaceholder { background:url(../images/blackboard.png) no-repeat; width:924px; height:599px; margin:0 car; padding:14px 0 75px 14px; cursor:crosshair; } Footstep four The Canvas Tag
Nosotros are going to insert the canvas tag correct into the blackboardPlaceholder. Identify the below code inside the 'blackboardPlaceholder' ID.
<!-- Canvas Begins --> <canvas id="drawingCanvas" top="532" width="897"> <p form="noscript">Nosotros're sorry, this web application is currently not supported with your browser. Please utilise an alternate browser or download a supported <br />browser. Supported browsers: <a href="http://world wide web.google.com/chrome">Google Chrome</a>, <a href="http://www.opera.com">Opera</a>, <a href="http://www.mozilla.com">Firefox</a>, <a href="http://www.apple.com/safari">Safari</a>, <br />and <a href="http://www.konqueror.org">Konqueror</a>. Too make certain your JavaScript is enabled.</p> </canvas> <!-- Canvas Ends -->
This is the exact width and peak of the canvass we are creating so no need to change that. Likewise, as I mentioned above, anything in between the canvas tags will be displayed only if JavaScript has been disabled, or the browser does not support canvas.
Side by side, let'south style the ID up a little bit. In your styles.css file, add:
#drawingCanvas { position:absolute; border:none; colour:#FFF; overflow:hidden; background-color:transparent; } #tempCanvas { position: absolute; width:897px; height:532px; overflow:hidden; } I will explain the #tempCanvas ID presently, when we begin writing the JavaScript.
Step v JavaScript Implementation
Permit's now make our canvass part the way it should. Begin by creating a new JS file, and naming information technology "canvas". Save this file within the 'JS' folder.
var context;
Side by side, we will add a function to determine if there is a canvas tag in the HTML document using the addEventListener and onLoad part. Paste this right underneath the variable we created.
// Check for the canvas tag onload. if(window.addEventListener) { window.addEventListener('load', function () { Now, allow'southward add some default variables and some error messages - if anything went wrong.
var canvas, canvaso, contexto; // Default tool. (chalk, line, rectangle) var tool; var tool_default = 'chalk'; function init () { canvaso = certificate.getElementById('drawingCanvas'); if (!canvaso) { alert('Error! The canvas element was not constitute!'); return; } if (!canvaso.getContext) { alarm('Error! No canvas.getContext!'); return; } // Create 2d sail. contexto = canvaso.getContext('2d'); if (!contexto) { alert('Fault! Failed to getContext!'); return; } // Build the temporary sail. var container = canvaso.parentNode; canvas = document.createElement('canvas'); if (!canvas) { alert('Error! Cannot create a new canvas chemical element!'); return; } canvass.id = 'tempCanvas'; sail.width = canvaso.width; canvas.tiptop = canvaso.height; container.appendChild(canvas); context = canvas.getContext('2d'); context.strokeStyle = "#FFFFFF";// Default line color. context.lineWidth = 1.0;// Default stroke weight. // Fill transparent canvas with night grey (So we can use the colour to erase). context.fillStyle = "#424242"; context.fillRect(0,0,897,532);//Top, Left, Width, Height of canvas. We've created some new variables and methods that will be used later.
The context.strokeStyle is the color of our stroke. We will brand the default '#FFFFFF', which is the hex value for white. Next is the context.lineWidth. This is the stroke of our line. We will leave the default value 'ane.0'. Now we will make a grey rectangle to use later on when we add the ability to save our paradigm. We'll fill the rectangle with gray or '#424242' and make it the verbal size of our canvas.
Standing on, let's create our drop down menu, where we tin select between chalk, a rectangle, or a line.
// Create a select field with our tools. var tool_select = document.getElementById('selector'); if (!tool_select) { alert('Error! Failed to go the select element!'); render; } tool_select.addEventListener('alter', ev_tool_change, fake); // Activate the default tool (chalk). if (tools[tool_default]) { tool = new tools[tool_default](); tool_select.value = tool_default; } // Event Listeners. sail.addEventListener('mousedown', ev_canvas, simulated); canvas.addEventListener('mousemove', ev_canvas, false); canvas.addEventListener('mouseup', ev_canvas, simulated); } // Go the mouse position. function ev_canvas (ev) { if (ev.layerX || ev.layerX == 0) { // Firefox ev._x = ev.layerX; ev._y = ev.layerY; } else if (ev.offsetX || ev.offsetX == 0) { // Opera ev._x = ev.offsetX; ev._y = ev.offsetY; } // Get the tool's effect handler. var func = tool[ev.type]; if (func) { func(ev); } } function ev_tool_change (ev) { if (tools[this.value]) { tool = new tools[this.value](); } } // Create the temporary sail on top of the sheet, which is cleared each time the user draws. office img_update () { contexto.drawImage(canvas, 0, 0); context.clearRect(0, 0, canvass.width, canvass.height); } var tools = {}; // Chalk tool. tools.chalk = part () { var tool = this; this.started = false; // Begin drawing with the chalk tool. this.mousedown = function (ev) { context.beginPath(); context.moveTo(ev._x, ev._y); tool.started = true; }; this.mousemove = role (ev) { if (tool.started) { context.lineTo(ev._x, ev._y); context.stroke(); } }; this.mouseup = role (ev) { if (tool.started) { tool.mousemove(ev); tool.started = false; img_update(); } }; }; We've but made the drawing function for the chalk! Obviously our canvas nevertheless won't work at this stage but we're most at that place!
Let'southward make our rectangle tool now.
// The rectangle tool. tools.rect = function () { var tool = this; this.started = false; this.mousedown = function (ev) { tool.started = true; tool.x0 = ev._x; tool.y0 = ev._y; }; this.mousemove = function (ev) { if (!tool.started) { return; } // This creates a rectangle on the canvas. var ten = Math.min(ev._x, tool.x0), y = Math.min(ev._y, tool.y0), west = Math.abs(ev._x - tool.x0), h = Math.abs(ev._y - tool.y0); context.clearRect(0, 0, canvas.width, canvas.peak);// Clears the rectangle onload. if (!w || !h) { return; } context.strokeRect(x, y, w, h); }; // Now when you select the rectangle tool, you tin can draw rectangles. this.mouseup = function (ev) { if (tool.started) { tool.mousemove(ev); tool.started = false; img_update(); } }; }; And now for the line tool.
// The line tool. tools.line = function () { var tool = this; this.started = imitation; this.mousedown = function (ev) { tool.started = true; tool.x0 = ev._x; tool.y0 = ev._y; }; this.mousemove = part (ev) { if (!tool.started) { return; } context.clearRect(0, 0, sheet.width, canvas.height); // Brainstorm the line. context.beginPath(); context.moveTo(tool.x0, tool.y0); context.lineTo(ev._x, ev._y); context.stroke(); context.closePath(); }; // At present y'all can draw lines when the line tool is seletcted. this.mouseup = part (ev) { if (tool.started) { tool.mousemove(ev); tool.started = imitation; img_update(); } }; }; And that just about wraps up our JavaScript! Now let'due south close the function and variables we created a while back by catastrophe with this:
init();
}, false); }
Footstep 6 Inserting The Tool Selection
Let'due south get back to our HTML page. Nosotros will now create the tool option using a bones HTML dropdown class tag.
Directly below the start of the 'blackboardPlaceholder' tag and right before our canvas tag, add the code below to create the dropdown tool choice.
<p><!-- Tool Selector --> <select proper noun="selector" id="selector"> <option value="chalk">Chalk</choice> <selection value="line">Line</option> <option value="rect">Rectangle</option> </select> </p>
And that's it! Now we have a drop down form, let's add some styling to information technology.
.noscript { padding:50px 30px 0 40px; width:820px; } #selector { position:accented; z-index:99999; margin-meridian:-30px; } select { font-family:Verdana, Geneva, sans-serif; font-size:12px; background-color:#EAEAEA; } The .noscript is the mode for the text in between the canvas tag that we never added higher up.
Step vii Changing The Color
Just to inform you lot, those are chalk pieces. I felt that due to my design skills, I had to inform yous what they were considering many people were telling me how they don't await remotely close to a piece of chalk :)
It's actually quite easy to alter the color in the HTML. All you demand to do is use the onclick role. Links, images, text, classes, etc. The function nosotros use to change the color is beneath.
onclick="context.strokeStyle = '#ff00d2';"
To change the color, just modify the hex color lawmaking in betwixt the parentheses. #FF00D2, used in a higher place, will change the stroke color to pink.
At present let'due south add the HTML markup for the chalk pieces.
<!-- Chalk Pieces --> <div id="whiteChalk_button"> <img src="images/white.png" width="71" height="17" onclick="context.strokeStyle = '#FFFFFF';" /> </div> <div id="redChalk_button"> <img src="images/red.png" width="71" height="17" onclick="context.strokeStyle = '#F00000';" /> </div> <div id="orangeChalk_button"> <img src="images/orangish.png" width="71" summit="17" onclick="context.strokeStyle = '#ff9600';" /> </div> <div id="yellowChalk_button"> <img src="images/yellow.png" width="71" summit="17" onclick="context.strokeStyle = '#fff600';" /> </div> <div id="greenChalk_button"> <img src="images/light-green.png" width="71" elevation="17" onclick="context.strokeStyle = '#48ff00';" /> </div> <div id="blueChalk_button"> <img src="images/blue.png" width="71" height="17" onclick="context.strokeStyle = '#001eff';" /> </div> <div id="pinkChalk_button"> <img src="images/pink.png" width="71" peak="17" onclick="context.strokeStyle = '#ff00d2';" /> </div>
Add the above code correct underneath the </canvas> tag.
Your HTML code should await like the following thus far.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <!-- External CSS Document(south) --> <link rel="stylesheet" type="text/css" href="css/styles.css" /> <title>Online Drawing Application | Web Pattern Deluxe</championship> <!-- Eternal JavaScript Document(s) --> <script blazon="text/javascript" src="js/canvas.js"></script> </head> <body> <!-- Wrapper Begins --> <div id="wrapper"> <div id="blackboardPlaceholder"> <p><!-- Tool Selector --><select name="selector" id="selector"><option value="chalk">Chalk</option><option value="line">Line</selection><option value="rect">Rectangle</pick></select></p> <!-- Canvas Begins --><canvas id="drawingCanvas" height="532" width="897"> <p grade="noscript">Nosotros're sorry, this web application is currently not supported with your browser. Please utilize an alternate browser or download a supported <br />browser. Supported browsers: <a href="http://www.google.com/chrome">Google Chrome</a>, <a href="http://www.opera.com">Opera</a>, <a href="http://www.mozilla.com">Firefox</a>, <a href="http://www.apple.com/safari">Safari</a>, <br />and <a href="http://www.konqueror.org">Konqueror</a>. Also make sure your JavaScript is enabled.</p></canvas> <!-- Canvass Ends --> <!-- Chalk Pieces --><div id="whiteChalk_button"><img src="images/white.png" width="71" top="17" onclick="context.strokeStyle = '#FFFFFF';" /></div> <div id="redChalk_button"><img src="images/red.png" width="71" superlative="17" onclick="context.strokeStyle = '#F00000';" /> </div> <div id="orangeChalk_button"><img src="images/orangish.png" width="71" height="17" onclick="context.strokeStyle = '#ff9600';" /> </div> <div id="yellowChalk_button"><img src="images/yellow.png" width="71" height="17" onclick="context.strokeStyle = '#fff600';" /></div> <div id="greenChalk_button"> <img src="images/greenish.png" width="71" height="17" onclick="context.strokeStyle = '#48ff00';" /></div> <div id="blueChalk_button"><img src="images/blueish.png" width="71" height="17" onclick="context.strokeStyle = '#001eff';" /></div> <div id="pinkChalk_button"><img src="images/pink.png" width="71" height="17" onclick="context.strokeStyle = '#ff00d2';" /></div> </div> </div> </torso> </html>
Step 8 Adding An Eraser
The eraser is simply an image that has the same stroke color equally the rectangle we created in the JavaScript, '#424242'. Copy and paste the HTML below the chalk pieces nosotros but created above.
<!-- Eraser --> <div id="eraser" onclick="context.strokeStyle = '#424242'; context.lineWidth = '22';"></div>
Step 9 Styling The Chalk And Eraser
Now let'due south add some styling to the chalk pieces and eraser earlier we moev whatever further. Add together the following to your styles.css file.
#redChalk_button { cursor:pointer; position:absolute; z-index:99999; top:620px; left:160px; } #greenChalk_button { cursor:pointer; position:absolute; z-index:99999; elevation:620px; left:400px; } #blueChalk_button { cursor:pointer; position:absolute; z-index:99999; peak:620px; left:480px; } #yellowChalk_button { cursor:pointer; position:absolute; z-index:99999; top:620px; left:320px; } #orangeChalk_button { cursor:pointer; position:accented; z-alphabetize:99999; top:620px; left:240px; } #pinkChalk_button { cursor:pointer; position:accented; z-index:99999; top:620px; left:560px; } #whiteChalk_button { cursor:pointer; position:absolute; z-index:99999; acme:620px; left:80px; } #eraser { position:absolute; background:url(../images/eraser.png) no-repeat; left: 737px; top: 568px; width: 139px; top: 67px; z-index:99999; cursor:arrow; } Step 10 Changing The Stroke Weight
Changing the stroke is just equally easy equally changing the color in the HTML. All you have to practise is use the 'onclick' function:
onclick="context.lineWidth = 'ane.0';"
'ane.0' is the smallest stroke allowed. You tin increment the stroke as much as you want.
Now let'due south add some stroke features to our HTML. Re-create and paste the code below into your HTML document. Y'all volition need to place this exterior the 'blackboardPlaceholder', immediately post-obit the closing div tag (before the wrapper ends).
<!-- Toggle Stroke Weight --> <img src="images/toggle.png" width="xvi" height="16" id="stroke-subtract" title="Decrease Stroke" onclick="context.lineWidth--;" /> <img src="images/toggle-expand.png" width="16" peak="16" id="stroke-add together" title="Increment Stroke" onclick="context.lineWidth++;" /> <!-- Stroke Weight Console --> <div id="strokeWeight"> <img src="images/stroke1.png" alt="1.0" class="stroke" width="xxx" height="32" onclick="context.lineWidth = 'i.0';" /> <img src="images/stroke2.png" alt="6.0" course="stroke" width="30" pinnacle="32" onclick="context.lineWidth = 'half-dozen.0';" /> <img src="images/stroke3.png" alt="ix.0" class="stroke" width="30" top="32" onclick="context.lineWidth = '9.0';" /> <img src="images/stroke4.png" alt="13.0" class="stroke" width="30" summit="32" onclick="context.lineWidth = '13.0';" /> </div>
Now some CSS:
#stroke-subtract { position:absolute; top:436px; left:-13px; z-alphabetize:999999; cursor:pointer; } #stroke-add { position:absolute; tiptop:436px; left:5px; z-index:999999; cursor:pointer; } #strokeWeight { background:url(../images/stroke-fashion.png) no-repeat; width:43px; acme:153px; position:absolute; top:456px; left:-18px; z-index:1; padding:8px 0 0 7px; } .stroke { cursor:pointer; margin-lesser:3px; } Step eleven The Relieve Feature
This is probably the most circuitous department of our tutorial. Nosotros'll exist using the prototype/data JavaScript function to save our epitome. But starting time, nosotros need an image library. Nosotros will employ the Canvas2Image and the Base64 Library, created by Jacob Seidelin at nihilogic.dk.
If you haven't already, you tin download these files here, and place them in your 'js' folder.
We need to modify the canvas.js file. Add together the following to the bottom of your file.
window.onload = function() { var bMouseIsDown = false; var oCanvas = document.getElementById("drawingCanvas"); var oCtx = oCanvas.getContext("2d"); var iWidth = oCanvas.width; var iHeight = oCanvas.height; role showDownloadText() { document.getElementById("textdownload").style.display = "block"; } function hideDownloadText() { document.getElementById("textdownload").manner.display = "none"; } function convertCanvas(strType) { if (strType == "PNG") var oImg = Canvas2Image.saveAsPNG(oCanvas, true); if (strType == "BMP") var oImg = Canvas2Image.saveAsBMP(oCanvas, true); if (strType == "JPEG") var oImg = Canvas2Image.saveAsJPEG(oCanvas, true); if (!oImg) { alert("Lamentable, this browser is not capable of saving." + strType + " files!"); return false; } oImg.id = "canvasimage"; oImg.style.edge = oCanvas.style.border; oCanvas.parentNode.replaceChild(oImg, oCanvas); howDownloadText(); } office saveCanvas(pCanvas, strType) { var bRes = false; if (strType == "PNG") bRes = Canvas2Image.saveAsPNG(oCanvas); if (strType == "BMP") bRes = Canvas2Image.saveAsBMP(oCanvas); if (strType == "JPEG") bRes = Canvas2Image.saveAsJPEG(oCanvas); if (!bRes) { alert("Deplorable, this browser is not capable of saving " + strType + " files!"); return faux; } } document.getElementById("convertpngbtn").onclick = office() { convertCanvas("PNG"); } document.getElementById("resetbtn").onclick = function() { var oImg = document.getElementById("canvasimage"); oImg.parentNode.replaceChild(oCanvas, oImg); hideDownloadText(); }} Essentially, when yous click the save button, it volition catechumen your canvas into a PNG, and from there, you lot will be able to right click and download the image. Pretty neat, right!?
At present let's add the HTML:
<!-- Save Image --> <div id="saveWrapper"> <div id="save"> <img src="images/save.png" alt="Save Image" width="16" peak="16" id="convertpngbtn" title="Relieve Image" /> </div> <div id="textdownload"> Correct click the prototype to download. <img src="images/cross.png" alt="Cancel" width="xvi" elevation="16" id="resetbtn" title="Continue Drawing" /> </div> </div>
Add the above code direct after the wrapper; this will create the save and clear buttons. Now we volition add together the CSS to style information technology upward a chip.
#saveWrapper { position:absolute; correct:0px; } #convertpngbtn { float:correct; margin-correct:40px; margin-tiptop:-10px; position:relative; z-index:9999; cursor:arrow; overflow:hidden; } #textdownload { display:none; position:absolute; font-family:Verdana, Geneva, sans-serif; color:#000; font-size:10px; float:right; margin-top:-10px; right:91px; width:250px; overflow:hidden; } Simply add this code to the styles.css stylesheet.
Step 12 The Advanced Color Table
To add more flexibility, nosotros should create a color tabular array, similar to the one used in Dreamweaver CS4.
So to practise this I figured information technology would be really quite easy. I would salve the to a higher place color table, and then use it equally a background prototype of a div id, and so inside, have a seperate div class for each colour with the aforementioned onclick role we used to a higher place. I shortly realized that this was not the best solution as it would create a mess in the HTML and would take forever to load each div. So instead I cam up with a new solution that soley consists of JavaScript. I would create each div dynamically in my JavaScript file, and insert the color code for each 'colour box' in an array. Then before I explain whatsoever further, we will do but that. Open your JavaScript file we have been working on, and at the very meridian of the file right underneath are context variable, create a new variable named "colorPalette". Then nosotros will begin the array. Each new line of colorsI seperated with 1 line of whitespace in the JavaScript. At that place are twelve columns full then we volition take a total of twelve sections in our array.
Here is the JavaScript:
var colorPalette = [ //Begin array of color tabular array hex color codes. "#000000","#000000","#000000","#000000","#003300","#006600","#009900","#00CC00","#00FF00","#330000","#333300","#336600","#339900","#33CC00","#33FF00","#660000","#663300","#666600","#669900","#66CC00","#66FF00", "#000000","#333333","#000000","#000033","#003333","#006633","#009933","#00CC33","#00FF33","#330033","#333333","#336633","#339933","#33CC33","#33FF33","#660033","#663333","#666633","#669933","#66CC33","#66FF33", "#000000","#666666","#000000","#000066","#003366","#006666","#009966","#00CC66","#00FF66","#330066","#333366","#336666","#339966","#33CC66","#33FF66","#660066","#663366","#666666","#669966","#66CC66","#66FF66", "#000000","#999999","#000000","#000099","#003399","#006699","#009999","#00CC99","#00FF99","#330099","#333399","#336699","#339999","#33CC99","#33FF99","#660099","#663399","#666699","#669999","#66CC99","#66FF99", "#000000","#CCCCCC","#000000","#0000CC","#0033CC","#0066CC","#0099CC","#00CCCC","#00FFCC","#3300CC","#3333CC","#3366CC","#3399CC","#33CCCC","#33FFCC","#6600CC","#6633CC","#6666CC","#6699CC","#66CCCC","#66FFCC", "#000000","#FFFFFF","#000000","#0000FF","#0033FF","#0066FF","#0099FF","#00CCFF","#00FFFF","#3300FF","#3333FF","#3366FF","#3399FF","#33CCFF","#33FFFF","#6600FF","#6633FF","#6666FF","#6699FF","#66CCFF","#66FFFF", "#000000","#FF0000","#000000","#990000","#993300","#996600","#999900","#99CC00","#99FF00","#CC0000","#CC3300","#CC6600","#CC9900","#CCCC00","#CCFF00","#FF0000","#FF3300","#FF6600","#FF9900","#FFCC00","#FFFF00", "#000000","#00FF00","#000000","#990033","#993333","#996633","#999933","#99CC33","#99FF33","#CC0033","#CC3333","#CC6633","#CC9933","#CCCC33","#CCFF33","#FF0033","#FF3333","#FF6633","#FF9933","#FFCC33","#FFFF33", "#000000","#0000FF","#000000","#990066","#993366","#996666","#999966","#99CC66","#99FF66","#CC0066","#CC3366","#CC6666","#CC9966","#CCCC66","#CCFF66","#FF0066","#FF3366","#FF6666","#FF9966","#FFCC66","#FFFF66", "#000000","#FFFF00","#000000","#990099","#993399","#996699","#999999","#99CC99","#99FF99","#CC0099","#CC3399","#CC6699","#CC9999","#CCCC99","#CCFF99","#FF0099","#FF3399","#FF6699","#FF9999","#FFCC99","#FFFF99", "#000000","#00FFFF","#000000","#9900CC","#9933CC","#9966CC","#9999CC","#99CCCC","#99FFCC","#CC00CC","#CC33CC","#CC66CC","#CC99CC","#CCCCCC","#CCFFCC","#FF00CC","#FF33CC","#FF66CC","#FF99CC","#FFCCCC","#FFFFCC", "#000000","#FF00FF","#000000","#9900FF","#9933FF","#9966FF","#9999FF","#99CCFF","#99FFFF","#CC00FF","#CC33FF","#CC66FF","#CC99FF","#CCCCFF","#CCFFFF","#FF00FF","#FF33FF","#FF66FF","#FF99FF","#FFCCFF","#FFFFFF" ];
And that's every colour in our colour table. At present let's add the JavaScript to make it work.
$(document).ready(function() { // Handles showing/hiding the color table $("#colorTable").hide(); $("#color").click(function() { $("#colorTable").prove(); }); $(document).click(office() { $("#colorTable").hide(); }); $("#color").click(function(event) { event.stopPropagation(); }); }); part LoadColorTable() { // Populate the colour picker table with colors specified in the 'colorPalette' array for (i = 0; i < colorPalette.length; i++) { var colorDiv = document.createElement("div"); colorDiv.className = "color"; colorDiv.id = "colorSwatch" + i; colorDiv.style.backgroundColor = colorPalette[i]; colorDiv.setAttribute("onclick", "SetColor(id);"); document.getElementById("colorTable").appendChild(colorDiv); }; } role SetColor(id) { // Gear up the colour of the drawing tool when a colour swatch is clicked context.strokeStyle = document.getElementById(id).style.backgroundColor; } Okay, so the code above, we offset by adding some functions to show or hibernate the colorTable ID in our HTML (which nosotros will get to in a moment). This is only basic jquery for when yous click the colorTable or anywhere exterior the colorTable it will hide the ID. At present nosotros will load the colorTable. Do exercise this nosotros will populate it with all of the color codes we added in the 'colorPalette' assortment. And finally to make everything work, nosotros will set the colour of the drawing tool when a colour swatch is clicked. To do this, we will only brand each color a course of 'color' and then employ the array to make each hex color value the background. And finally apply a function so when a color is clicked, the context.strokeStyle will equal the background image.
And for the HTML markup, yous volition add together the following code immediately after the wrapper is started in your HTML.
<!-- Color Table (controlled in JavaScript) --> <div id="colorTable"></div> <!-- Toggle Color Button --> <div id="color" title="Toggle Color"> <img src="images/color-pointer.png" alt="Toggle Color" width="16" top="16" /> </div>
And now permit's add some style to our color table.
#colorTable { width:231px; elevation:132px; position:absolute; margin-height:8px; z-alphabetize:999999; right:80px; background-colour: #000000; display:none; cursor:arrow; } .colour { position:relative; elevation:7px; width:7px; float:left; padding:1px; margin:1px; } .color:hover{ border:solid 1px #FFF; margin:0px; } Add together this anywhere into your styles.css file you created a while dorsum.
And there you have information technology! Now nosotros have over 200 dissimilar colors that nosotros tin choose from!
Step 13 Using the Reload Part to Articulate the Canvas
Now we will create a simple push button to articulate the canvas. The easiest way to exercise this is simply refresh the page. And so we are going to use a office I am sure you are all familiar with. If non, the beneath code will merely refresh the page using JavaScript.
<a href="javascript:location.reload(true)">Clear</a>
That's it. So now let'due south add together it into our HTML. Nosotros will use the paradigm in your 'images' binder that looks like the radioactive symbol. I'g not sure why I used a radioactive symbol for this, but I couldn't find any other icon in the icon pack to use, so this will suffice.
Add the following image to you HTML below. Because it has an accented position it really doesn't matter where yous place it as long as place it exterior of the 'blackboardPlaceholder' and within the 'wrapper'. So but to make the lawmaking look "in society" we are going to place the following code correct subsequently our ID "color".
<!-- Articulate Canvas Push button --> <div id="nuke" title="Clear Canvas"> <a href="javascript:location.reload(true)"> <img src="images/burn down.png" alt="Articulate Canvass" width="xvi" top="16" /> </a> </div>
And of class, some CSS:
#nuke { position:absolute; cursor:pointer; margin-summit:-10px; right:100px; } And there yous have it. A nice looking 'clear' push button.
Step fourteen Adding an Extra Characteristic to the Stroke Bill of fare
Later on I completed this drawing application I withal felt that the weight of the strokes you were able to choose were still a bit depression. So I though I would make a new little function for that. I will non remove the stroke menu nosotros already currently accept, I will merely add on to it a bit. My idea was to accept a plus and a minus button. The plus button would increase the stroke weight by 1, and the minus push would obviously decrease the stroke past one.
Then in gild to exercise this we will find some nice plus and minus buttons in our icon pack to use. We will then write the HTML write above the ID 'storkeWeight'.
<!-- Toggle Stroke Weight --> <img src="images/toggle.png" width="xvi" height="16" id="stroke-subtract" title="Decrease Stroke" onclick="context.lineWidth--;" /> <img src="images/toggle-aggrandize.png" width="16" height="sixteen" id="stroke-add" title="Increment Stroke" onclick="context.lineWidth++;" />
The onclick office is a scrap different than what we used before, basically the '--' and the '++' values will simply add or subtract ane from the default value. The default value is 1.0 and then when you click the plus button, the stroke will now be 2.0, a bit bigger than the default.
And now the CSS:
#stroke-subtract { position:absolute; top:436px; left:-13px; z-index:999999; cursor:arrow; } #stroke-add { position:absolute; superlative:436px; left:5px; z-index:999999; cursor:pointer; } Footstep 15 Adding Tooltips
In club to make are application more user-friendly we will need to add some titles to all of our buttons. Luckily I have already included all of the code in the HTML, you just didn't observe it. Basically all of our icons in the HTML code take the title tag. Y'all all should know what championship tags are, but we are going to employ those tags to implement a rather overnice jQuery tooltip effect known as Tipsy. I take used Tipsy many times in other projects and it is really a great plugin. You lot volition need to download the Tipsy files hither. Place the 'tipsy.css' file in your css binder, the 'jquery.tipsy.js' in your js folder, and the 'tipsy.gif' in your images folder if it is not in that location already.
You will need to add the jQuery library to your header. Here is the direct link to the latest jQuery library. Yous can link straight to this or download information technology to your 'js' folder:
http://ajax.googleapis.com/ajax/libs/jquery/ane.four.2/jquery.min.js
At present we volition demand to call the JavaScript file for tipsy. Make sure when you telephone call this in your header, the jQuery script comes before this script. It should similar like this:
<script blazon="text/javascript" src="js/jquery.tipsy.js"></script>
And then call the 'tipsy.css' file in your HTML. That should await like the following:
<link rel="stylesheet" type="text/css" href="css/tipsy.css" />
And now let's call the actually JavaScript. Place this in your header beneath all of the external JavaScript and CSS sources.
<script type='text/javascript'> $(function() { $('#nuke').tipsy({gravity: 'south'}); $('#color').tipsy({gravity: 's'}); $('#convertpngbtn').tipsy({gravity: 's'}); $('#resetbtn').tipsy({gravity: 'south'}); $('#stroke-subtract').tipsy({gravity: 's'}); $('#stroke-add').tipsy({gravity: 's'}); }); </script> You volition also need to add one more matter to your styles.css file to fancy upward the tooltips a little scrap:
.tooltip{ position: accented; height: 0; left: 0; z-index: three; brandish: none; background-color:#F00; } Wrapping It Upward
And that just nearly wraps it up! Congratulations. Please practice let me know if yous have whatever questions or thoughts on means to improve this application. Thanks for reading!
Source: https://code.tutsplus.com/tutorials/how-to-create-a-web-based-drawing-application-using-canvas--net-14288
Posted by: wrightititan79.blogspot.com

0 Response to "How To Draw On A Canvas"
Post a Comment