Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to make Drawings with Html

HTML5 Canvas

HTML5 Canvas is used to draw graphics on fly using javascript. The canvas element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images. To learn more about canvas follow this link.

Just use FULL CODE at bottom of tutorial

Example: To write some thing inside canvas use this

<canvas id="paintSamp1" style="height: 150px;width:350px; margin:auto;"></canvas>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript"> var canvasa = document.getElementById('paintSamp1'); var context1 = canvasa.getContext('2d');

context1.font = 'normal 18px Arial';
context1.textAlign = 'center';
context1. textBaseline = 'middle';
context1.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values
context1.fillText('Welcome to trinity tuts!', 150, 50); // text and position

In this above example i first create canvas tag and set height and width and assign id to canvas. After this i include jQuery from google cdn. Now inside <script> first i find canvas in document i need to write something after that call some predefined method like font, textAlign etc. to make my word look nice.

Now i explain you how to make a simple web based paint application

Create a <canvas> inside body.

`<canvas id="drawingPaper" width="560" height="280"></canvas>
Create some option we used for drawing like pen size, clear canvas, eraser etc.

<button id="clrcanvas">Clear Canvas</button>
<button id="erasecanvas">Eraser</button>
<button id="pencanvas">Pen</button>

Include jQuery Library file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Now we write some javascript code to get or application working.

<script type="text/javascript">
window.onload = function() { $('.selectedColor').trigger('click'); }
$(function() {

In above code first i get my selected color to draw image so i trigger event to get that thing.

window.onload = function() {
Now get our selected color i get my canvas ready to draw picture on it

c = document.getElementById('drawingPaper')
context = c.getContext("2d");
Now we need to handle some events over canvas like

When user mouse is down and move over canvas you need to start create image or when user mouse is up and leave you need to stop. In above code i create two main function which are responsible to get mouse position and to draw image.

Complete Code:

<!DOCTYPE html>
<title>Demo - HTML5 based web application for drawing using canvas</title>



Add cool pink to purple gradient to the background

Here is the code below

body {
min-width: 800px;
background: #ff00cc;
background: -webkit-linear-gradient(to right, #333399, #ff00cc);
background: linear-gradient(to right, #333399, #ff00cc);