Skip to content Skip to sidebar Skip to footer

Clear Canvas Drawpad Jquery

I'm using the drawing pad (pen tool) plugin of Jquery to draw with different colors and having an image in the canvas as background. My purpose is to have a button to clear the dra

Solution 1:

This answer is an improvisation on my previous answer at https://stackoverflow.com/a/67155647/3706717

So we have new requirement: delete/clear previous drawings

There are some possible approach here:

  • @sinisake in comment suggested to reload the background so that we have fresh canvas with only the background intact (but for some reason, white doodle make the background gone)
  • the library must have "delete" or "erase" doodle feature (which it didn't have)
  • save each changes of the drawing when user click "save", so that user can "undo" to previous version of the drawing (like git's git commit and git reset command), I'll be using this approach in my answer

Ideally, you should use server-side language and persistent storage (e.g.: database) to store user's doodling history. But in this case, to simulate such thing I'll be using javascript's localStorage API https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

So every time I'm calling localStorage API, just assume that I'm calling some ajax to some endpoint.

Fiddle: https://jsfiddle.net/0da572jy/3/

Here is stack fiddle (modified because browser didn't allow stack fiddle to use localStorage)

// polyfill for localStorage APIvar localStorage1 = {
  items: {},
  removeItem: function(key) {
    window.localStorage1.items[key] = null;
  },
  getItem: function(key) {
    returnwindow.localStorage1.items[key];
  },
  setItem: function(key, val) {
    returnwindow.localStorage1.items[key] = val;
  },
}
//window.localStorage = localStorage1;window.localStorage1 = localStorage1;



$(document).ready(function() {
  
  
  $("#save").click(function() {
  
    // I already explained the #save logic in https://stackoverflow.com/a/67155647/3706717//console.log("save");var base64Image = $("#target canvas").get(0).toDataURL();
    //console.log(base64Image);
    $("#outputBase64FormInput").val(base64Image);
    $("#outputBase64").html(base64Image);
    
    // load/read saved states/historiesvar savedImageJson = window.localStorage1.getItem("savedImage");
    //console.log(savedImageJson);// if the history is undefined, create empty arrayif(savedImageJson == null || typeof savedImageJson == "undefined") savedImageJson = "[]";
    
    // parse the historyvar savedImageArr = JSON.parse(savedImageJson);
    
    // add current state as a new item to history
    savedImageArr.push(base64Image);
    
    // save the modified (added history)window.localStorage1.setItem("savedImage", JSON.stringify(savedImageArr));
    
    $("#numOfSavedHistory").html( savedImageArr.length );
  });
  
  // clear button just clears the localStorage (or any kind of API you use for persistent storage
  $("#clear").click(function() {
    //console.log("save");window.localStorage1.removeItem("savedImage");
    $("#numOfSavedHistory").html( 0 );
  });
  
  
  // undo last change (rollback to last state when you clicked save)
  $("#undo").click(function() {
    // clear canvas (to prevent white ink bug that also clears the background)
    canvas.width = canvas.width;
    
    //console.log("undo");// load/read saved states/historiesvar savedImageJson = window.localStorage1.getItem("savedImage");
    //console.log(savedImageJson);// if the history is undefined, create empty arrayif(savedImageJson == null || typeof savedImageJson == "undefined") savedImageJson = "[]";
    
    // parse the historyvar savedImageArr = JSON.parse(savedImageJson);
    
    // delete last item in history
    savedImageArr.pop();
    
    // save the modified (pop'ed history)window.localStorage1.setItem("savedImage", JSON.stringify(savedImageArr));
    
    // draw old picture on canvasvar imageOld = newImage();
    imageOld.src = savedImageArr[savedImageArr.length-1];
    imageOld.onload = function() {
      contextCanvas.drawImage(imageOld, 0, 0);
    };
    
    $("#numOfSavedHistory").html( savedImageArr.length );
  });
  
  

  // set backgroundvar urlBackground = 'https://picsum.photos/id/100/500/400';
  var imageBackground = newImage();
  imageBackground.src = urlBackground;
  //imageBackground.crossorigin = "anonymous";
  imageBackground.setAttribute('crossorigin', 'anonymous');
  $("#target").drawpad();
  var canvas = $("#target canvas").get(0);
  var contextCanvas = canvas.getContext('2d');
  imageBackground.onload = function(){
    contextCanvas.drawImage(imageBackground, 0, 0);
    $("#clear").trigger("click"); // clear previous drawings when page refreshed
    $("#save").trigger("click"); // save the first image (background only)
  }
  
});
body {background-color:rgb(248, 255, 227)}
        #target {
        width:500px;
        height:400px;
        }
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Document</title><linkhref="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.css" /><scriptsrc="https://code.jquery.com/jquery-3.5.1.min.js"></script><scriptsrc="https://cnbilgin.github.io/jquery-drawpad/jquery-drawpad.js"></script></head><body><buttonid="undo">Undo</button><buttonid="save">Save</button><buttonid="clear">Clear Saved Picture</button><spanid="numOfSavedHistory">0</span><divid="target"class="drawpad-dashed"></div><divid="outputBase64"></div></body></html>

Post a Comment for "Clear Canvas Drawpad Jquery"