Reputation: 587
How can I save a canvas image to a database?
I have a signature pad with a save button which opens a new window and displays the image when clicked. I would like to change the behavior of the button so that it saves the image to a database in order to be displayed later.
I'm having trouble getting the Data URL to send to the next page where I can process it to be inserted to the database.
I'm using phpMyAdmin.
Here's the index.html
file:
<body onselectstart="return false">
<div id="signature-pad" class="m-signature-pad">
<div class="m-signature-pad--body" >
<canvas>
</canvas>
</div>
<div class="m-signature-pad--footer">
<div class="description">Sign above</div>
<button type="button" class="button clear" data-action="clear">Clear</button>
<button type="button" class="button save" data-action="save">Save</button>
</div>
</div>
<script src="js/signature_pad.js"></script>
<script src="js/app.js"></script>
</body>`
And here is app.js
:
var wrapper = document.getElementById("signature-pad"),
clearButton = wrapper.querySelector("[data-action=clear]"),
saveButton = wrapper.querySelector("[data-action=save]"),
canvas = wrapper.querySelector("canvas"),
signaturePad;
// Adjust canvas coordinate space taking into account pixel ratio,
// to make it look crisp on mobile devices.
// This also causes canvas to be cleared.
function resizeCanvas() {
// When zoomed out to less than 100%, for some very strange reason,
// some browsers report devicePixelRatio as less than 1
// and only part of the canvas is cleared then.
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext("2d").scale(ratio, ratio);
}
window.onresize = resizeCanvas;
resizeCanvas();
signaturePad = new SignaturePad(canvas);
clearButton.addEventListener("click", function (event) {
signaturePad.clear();
});
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
window.open(signaturePad.toDataURL());
}
});
Upvotes: 0
Views: 3120
Reputation: 587
Just found an answer to this. and i think i should put the answer. other people might have the same problem.
to send DataURL to the next page . i just change my code
from
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
window.open(signaturePad.toDataURL());
}
});
to
saveButton.addEventListener("click", function post (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
document.body.innerHTML += '<form id="form" action="newpage.php" method="post"><input type="hidden" name="image" value="'+signaturePad.toDataURL()+'"></form>';
document.getElementById("form").submit();
}
});
just added a form and hidden input in javascript . now it can be retrieve to other page using $_POST
Upvotes: 1