Today I returned to my hostel after a 2 week long Diwali Break. Well, since it was Diwali it was obvious that I wouldnot be doing a single bit of coding and I am not complaining, but the last 3 days at home were free so I thought of getting in the mood slowly. So I picked up an old painting application that i had developed.
The previous one was a simple jQuery based application and did not have a feature to save your work so all the Davincis and Picassos out there could not show others their creations. So I thought of making the same app but on HTML Canvas element as it was very easy to save what you did!
This time again it was very easy to make the JQuery code that was used to paint. While it took me a long time setting up the positioning of the objects.Let me share some code needed to get the canvas up and running.
HTML:
<canvas id="can" width="500" height="500">
CSS:
#can
{
border:1px solid black;
}
JQuery/Javascript
var dodraw = false;
$("#can").mouseover(function(e){
if(dodraw==true)
{
ctx.lineWidth=size;
ctx.beginPath();
ctx.moveTo(e.PageX,e.PageY);
ctx.lineTo(e.PageX-1,e.PageY-1);
ctx.stroke();
}});
This code should be enough to get your canvas be able to draw stuff. You can further add features and modify the code as required.
I have currently added eraser,brush,save, new and size +/- buttons to the page.
The demo is available here:Open World
Tweet
The previous one was a simple jQuery based application and did not have a feature to save your work so all the Davincis and Picassos out there could not show others their creations. So I thought of making the same app but on HTML Canvas element as it was very easy to save what you did!
This time again it was very easy to make the JQuery code that was used to paint. While it took me a long time setting up the positioning of the objects.Let me share some code needed to get the canvas up and running.
HTML:
<canvas id="can" width="500" height="500">
CSS:
#can
{
border:1px solid black;
}
JQuery/Javascript
var dodraw = false;
var size=15; | ||||||||
var canvas = document.getElementById("can"); | ||||||||
var ctx = canvas.getContext('2d'); | ||||||||
ctx.StrokeStyle="blue"; | ||||||||
ctx.lineCap="round"; | ||||||||
$("#can").mousedown( | function(e){dodraw=true; | |||||||
ctx.lineWidth=size; | ||||||||
ctx.beginPath(); | ||||||||
ctx.moveTo(e.PageX,e.PageY); | ||||||||
ctx.lineTo(e.PageX-1,e.PageY-1); | ||||||||
ctx.stroke();}}); | ||||||||
$("#can").mousedown( dodraw=false;) | ||||||||
if(dodraw==true)
{
ctx.lineWidth=size;
ctx.beginPath();
ctx.moveTo(e.PageX,e.PageY);
ctx.lineTo(e.PageX-1,e.PageY-1);
ctx.stroke();
}});
This code should be enough to get your canvas be able to draw stuff. You can further add features and modify the code as required.
I have currently added eraser,brush,save, new and size +/- buttons to the page.
The demo is available here:Open World
Tweet