I’m using jSignature, which is a jQuery plugin for adding web signature functionality. I’m trying to allow the user to utilize multiple colors on the canvas and export a svg file. The issue is the user can utilize multiple colors on the canvas, however each time they change colors (with the class “changeColor” the variable “data”, which contains the data needed to save the svg is reset and thus it doesn’t match the canvas.
jSignature library: https://github.com/brinley/jSignature
After each color change data resets to:
image/svg+xml,<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="0" height="0"></svg>
My code:
<td style='background:#f0e4b0;id="#f0e4b0" class='changeColor'></td>
<td style='background:#b6e61e;id="#b6e61e" class='changeColor'></td>
<div id="signature"></div>
<textarea id='output' name='sig'></textarea>
<button id="clear">Clear</button>
<button type="button" onclick="download()">Save</button>
<script>
$(document).ready(function() {
// Initialize jSignature
var pen = '#000000';
var $sigdiv = $("#signature").jSignature({
'UndoButton' : false,
'color' : pen
});
$('.changeColor').on('click', function(event) {
// $('#signature').jSignature("reset");
pen = $(this).attr('id');
//update settings
$("#signature").jSignature('updateSetting', "color", pen,true);
});
$('#clear').click(function () {
$('#signature').jSignature("reset");
});
$('#signature').change(function() {
var data = $sigdiv.jSignature('getData', 'svg');
// Storing in textarea
$('#output').val(data);
// Alter image source
$('#sign_prev').attr('src', "data:" + data);
$('#sign_prev').show();
});
});
</script>
<script>
function download(){
var text = document.getElementById("output").value;
var blob = new Blob([text], { type: "text/plain"});
var anchor = document.createElement("a");
anchor.download = "signature.svg";
anchor.href = window.URL.createObjectURL(blob);
anchor.target ="_blank";
anchor.style.display = "none";
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
}
</script>