Wednesday 13 April 2016

drawing signature using canvas in jquery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script>
    var mousePressed = false;
var lastX, lastY;
var ctx;

function InitThis() {
    ctx = document.getElementById('myCanvas').getContext("2d");

    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        mousePressed = false;
    });
        $('#myCanvas').mouseleave(function (e) {
        mousePressed = false;
    });
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = 'black';
        ctx.lineWidth = '3';
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x; lastY = y;
}
   
function clearArea() {
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
function imgcreate() {
//to append image in body
var can = document.getElementById('myCanvas');
var ctx = can.getContext('2d');
//ctx.fillRect(50,50,50,50);
var img = new Image();
img.src = can.toDataURL();
$("#imgct").html(img);
//image upload
var Pic = document.getElementById("myCanvas").toDataURL("image/png");
     $('#sign').val(Pic);
    }
</script>

<body onLoad="InitThis();">
<form class="" action="form-submit.php" method="post">
<canvas id="myCanvas" width="500" height="200" style="border:2px solid black"></canvas>
<br /><br />
        <button onClick="javascript:clearArea();return false;">Refresh</button>
<input type="submit" value="Save" name="save" onMouseOver="return imgcreate();">
</form>
<div id="imgct"></div>
</body>
For upoad image to server create a php file with "form-submit.php" name. And use below code to save createed image :-
<?php
file_put_contents('images/test.png', base64_decode(substr($_POST['sign'], strpos($_POST['sign'], ",")+1)));
?>
After submit form image will be saved in images folder.

No comments:

Post a Comment