Masood Salik
Masood Salik

Reputation: 139

How can I clear the drawing canvas in JavaScript?

I am new to HTML. Just for the fun. I was making a drawing canvas in HTML by watching a tutorial on YouTube.

The code is simulated here: https://jsfiddle.net/MasoodSalik/yr1ezp4x/

I am facing 2 problems:

  1. When I Clear the canvas, The brush does not work properly as shown in image.

  2. When I draw or overshoot the edges of the canvas, brush remains dragging in canvas. I want it to stop drawing as it touches the edges. How can I do it?

    Drawing Canvas Problem brush

    *{
      -moz-box-sizing: border-box;
       box-sizing: border-box;
      font-family:sans-serif;
    
      user-select: none;
      -webkit-user-select:none;
       user-select: none;
    
    }
    
    
    #toolbara{
     width :329px;
     height :40px;
      padding:10px;
      position: relative;
      top:0px;
      background-color:#2f2f2f;
      color: white;
      }
    
    
    .radcontrol{
        width : 30px;
       height : 20px;
       background-color:#4f4f4f;
       display:inline-block;
       text-align:center;
    }
    
    #rad{
      float:left;
    }
    #colour{
     //position: relative;
      float:center;
    }
    
    .swatch{
      width:20px;
      height:20px;
      border-radius:10px;
      box-shadow: inset 0px 2px 0px rgba(255,255,255,0.5), 0px 2px 2px rgba(0,0,0,0.5);
      display:inline-block;
      margin-left:5px;
      margin-bottom:50px;
      background-color:cyan;
    }
    .swatch.active{
      border:2px solid white;
       box-shadow: inset 0px 1px 2px rgba(0,0,0,0.5) ;
    
    }
    #save{
        background-color: #4f4f4f;
       // width: 50px;
       padding: 5px;
       position: relative;
      float :right;
      top:-45px;
      right: 60px;
      margin-right:0px;
    }
    #save:hover{
      background-color: #818181;
    
    }
    
    #clear{
        background-color: #4f4f4f;
       // width: 50px;
       padding: 5px;
       position: relative;
      float :right;
      top:-45px;
      right: -40px;
     // margin-right:0px;
    }
    #clear:hover{
      background-color: #818181;
    
    }
    
    </style>
    
    
    <canvas id="canvas" width="325" height="500" style="border:2px solid">
    <p>Your browser doesn't support canvas.</p>
    </canvas>
    
    <div id ="toolbara">
        <div id="rad">
            Radius <span id="radval">1</span>
          <div id="decrad" class="radcontrol">-</div>
           <div id="incrad" class="radcontrol">+</div>
         </div>
         <div id="colors">
         </div>
         <div id="save"> Save </div>
         <div id="clear"> Clear </div>
    </div>
    
    <script>
    
    var canvas=document.getElementById('canvas');
    var context=canvas.getContext('2d');
    var radius=5;
    var dragging=false;
    
    context.beginPath();
    context.rect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "white";
    context.fill();
    context.beginPath();
    
    context.lineWidth=radius*2;
    
    var putPoint = function(e){
        if(dragging) {
        context.lineTo(e.offsetX, e.offsetY);
        context.stroke();
        context.beginPath();
        context.arc(e.offsetX, e.offsetY, radius, 0, Math.PI*2);
         context.fill();
        context.beginPath();
        context.moveTo(e.offsetX, e.offsetY);
    }
    }
    
    var engage=function(e)
    { dragging=true;
       putPoint(e);
    }
    
    var disengage=function()
    {   
     dragging=false;
    context.beginPath();
    }
    
        canvas.addEventListener('mousedown',engage);
        canvas.addEventListener('mouseup',disengage);
        canvas.addEventListener('mousemove',putPoint);
    
     var setRadius = function (newRadius) {
                    if (newRadius < minRad) newRadius = minRad;
                    else if (newRadius > maxRad) newRadius = maxRad;
                    radius = newRadius;
                    context.lineWidth = radius * 2;
    
                    radSpan.innerHTML = radius;
                }
    
      ////////////////////////////////////////
     var minRad = 1,
                    maxRad = 10,
                    defaultRad = 1,
                    interval = 1,
                    radSpan = document.getElementById('radval'),
                    decRad = document.getElementById('decrad'),
                    incRad = document.getElementById('incrad');
    
                decRad.addEventListener('click', function () {
                    setRadius(radius - interval);
                });
                incRad.addEventListener('click', function () {
                     setRadius(radius < interval ? interval : radius + interval);
                });
    
                setRadius(defaultRad);
      //////////////////////////////////////////////////////
    
    var colors = ['black', 'white', 'red', 'yellow', 'green', 'blue']; //Color array to select from
    /*Handles the creation of color*/
    for(var i=0, n=colors.length;i<n; i++){
    var swatch = document.createElement('nav');
    swatch.className = 'swatch';
    swatch.style.backgroundColor = colors[i];
    swatch.addEventListener('click',setSwatch);
    document.getElementById('colors').appendChild(swatch);
    }
    /*set color*/
    function setColor(color){
    context.fillStyle = color;
    context.strokeStyle = color;
    var active = document.getElementsByClassName('active')[0];
    if(active){
    active.className = 'swatch';
    }
    }
    function setSwatch(e){
    //identify swatch
    var swatch = e.target;
    //set color
    setColor(swatch.style.backgroundColor);
    //give active class
    swatch.className += ' active';
    }
    setSwatch({target: document.getElementsByClassName('swatch')[0]}); //set default swatch
    
    //////////////////////////////////////
    
     var button = document.getElementById('save');
                button.addEventListener('click', saveImage)
    
     function saveImage()          
     {     //   context.clearRect(0, 0, canvas.width, canvas.height);
                  var data = canvas.toDataURL();
    
                 window.open(data,'_blank,','location=0,menubar=0')
                 //  button.href = dataURL;
                };
    
     var butonclear = document.getElementById('clear');
                butonclear.addEventListener('click', clearImage)
    
     function clearImage()          
     {      
                context.clearRect(0, 0, canvas.width, canvas.height);
     context.beginPath();
    context.rect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "white";
    context.fill();
    context.beginPath();
    context.moveTo(e.offsetX, e.offsetY);
    
    
          };          
    
    </script>
    
    
    <!link rel="stylesheet" type="text/css" href="https://googledrive.com/host/0B7ZbA61nROnAMkFzSDVoOWdCWkk/noselect.css"></!link></!link>`
    

Upvotes: 1

Views: 376

Answers (1)

Kuba
Kuba

Reputation: 1455

  1. Brush doesn't work properly cause when you call clearImage() you are changing context.fillStyle to white, also context.moveTo(e.offsetX, e.offsetY); it's unnecessary. Look at that reproduce https://jsfiddle.net/yr1ezp4x/2/

  2. There you will have a bit more work. Inside functions triggered by mouse events you have to check if mouse is over your canvas.

Upvotes: 3

Related Questions