Canvas- Web Paint, Draw Shapes with Mouse Cursor

Written by @m_k_amin 25 June 2013

You should have seen paint program on the PC and other devices. HTML5 Canvas has also ability to detect mouse movements and draw lines when the mouse moves while its button is pressed. So you can have your own paint program on your website. For example you can get users signature and their handwritings. It's cool, isn't it? The following example shows how to make an HTML5 Canvas paint program and use colors. We have ignored many features because of the simplicity but you can easily add a color panel, transparency option and etc. to it. Press you mouse and move it and Enjoy!

Code Snippet:

                                                
                                                <!-- this script is provided by www.html5freecode.com coded by: Kerixa Inc. -->
<!-- This Script is from www.html5freecode.com, Coded by: Kerixa Inc-->
<canvas id="myCanvas" width="400" height="230" onmouseup="release()" onmousedown="lc=1" onmousemove="Draw(event)" onclick="putPoint(event)"
style="cursor:url('http://html5freecode.com/files/html5-paint-cursor.cur'), pointer"></canvas>
<script>
    var cnv = document.getElementById('myCanvas')
    var ctx = cnv.getContext('2d')
    
    var lc=0
    var prX=-1
    var prY=-1
	var dot= ctx.createImageData(2,2)
	for (i=0; i<dot.data.length; i+=4){
		dot.data[i+0]=0
		dot.data[i+1]=160
		dot.data[i+2]=230
		dot.data[i+3]=255
	}

function release(){
	lc=0
	prX=-1
}

function putPoint(event){
		var bb, x, y
		bb = cnv.getBoundingClientRect()
		x = (event.clientX-bb.left) * (cnv.width/bb.width)
		y = (event.clientY-bb.top) * (cnv.height/bb.height)
		ctx.putImageData(dot,x,y)
}

function Draw(event){
	if(lc==1){
		var bb, x, y
		bb = cnv.getBoundingClientRect()
		x = (event.clientX-bb.left) * (cnv.width/bb.width)
		y = (event.clientY-bb.top) * (cnv.height/bb.height)
		if (prX!=-1){
			ctx.beginPath()
			ctx.moveTo(prX,prY)
			ctx.lineTo(x,y)
			ctx.lineWidth=2
			ctx.closePath()
			ctx.strokeStyle='rgb(0,160,230)'
			ctx.stroke()
		}
		prX=x
		prY=y
	}
}

</script>
<div style="text-align: left"><font face="Tahoma"><br><a target="_blank" href="http://www.html5freecode.com"><span style="font-size: 8pt; text-decoration: none">HTML5 Free Code</span></a></font></div><a target='_blank' href='www.html5freecode.com' style='font-size: 8pt; text-decoration: none'>Html5 Free Codes</a>                                                
                                            

Example:


About @m_k_amin

This user is pending a biography.

M

Comments


Here you can leave us commments. Let us know what you think about this code tutorial!

0 / 300

TRENDING POST
1
2
3
4
5
VISITORS
Online Users: 12
Recent Members: FOTPU
advertisement 2