Monday 22 April 2019

Create a Drawing Board using Html5 Canvas and draw using mouse

In this post we are going to see  how to create a drawing board using Html5 Canvas and angular.This sample will make users to draw a free flow diagram while just drag the mouse over canvas.

Html
*****
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="style.css">
    <script src="angular.js"></script>
    <script src="app.js"></script>
</head>
<body>

    <div style="margin-left: 400px;">
        <h1>Drawing board, click and drag to draw</h1>
        <canvas width="500" height="500" id="drawingarea" free-flow-drawing></canvas>
    </div>
</body>
</html>

style.css
*********
#drawingarea{
    border-bottom: 1px solid rgba(0,0,0,0.3);    background-color: #FFF;    box-shadow: 0 9px 20px -5px rgba(0,0,0,0.8);}

JS
***
Below directive will draw the canvas container when ever user click and draw above container

var app = angular.module("app",[]);
app.directive('freeFlowDrawing',[function () {
return {
    restrict:'A',    link:function(scope,element,attr){
        var Drawingctx = element[0].getContext('2d');        var oldX;        var oldY;        var drawing = false;                function Draw(ox, oy, nx, ny) {
            Drawingctx.moveTo(ox,oy);            Drawingctx.lineTo(nx,ny);            Drawingctx.lineWidth = 8;            Drawingctx.strokeStyle = "blue";            Drawingctx.stroke();        }
        
        element.bind('mousedown',function (event) {
            oldX = event.offsetX;            oldY = event.offsetY;            Drawingctx.beginPath();            drawing = true;        });
        element.bind('mousemove',function (event) {
            if(drawing) {
                var newX = event.offsetX;                var newY = event.offsetY;                Draw(oldX,oldY,newX,newY);                oldX = newX;                oldY = newY;            }
        });
        element.bind('mouseup',function (event) {
            drawing = false;        });
    }
}
}]);

Output:
******






From this post you can learn how to create a drawing board using canvas and draw using mouse.

3 comments:

  1. Thanks for sharing such worthy content, this information is useful for knowledge seekers. Waiting for a more upcoming post like this.
    Graphic Designer Roles
    What Can Graphic Designers Do

    ReplyDelete
  2. Wonderful Blog!!! Waiting for your upcoming data... thanks for sharing with us.
    How to Start Software Testing Career
    Career in Software Testing

    ReplyDelete