I have managed to save a canvas as an image, using javaScript and Ajax, but I want or would like a dialog box not to appear to choose the destination folder, but rather to save it in a pre-established path.
Code block attached:
<script type="text/javascript">
function guardar() {
var link = document.createElement('a')
link.download = "firma";
link.href = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
link.click();
}
</script>
<button onclick="guardar()" id="convertir">Convertir</button>
In that code block, I define the function to convert to image, but I need to further automate this process, by saving the image to a preset path on a server using PHP and the function call will be made at the same time the administrator gives register a user.
I also have the question of how can I upload the image to the server? I need to save the signature in a database, I have the doubt of whether to upload the image to the database or in the database to save the path of the image.
Based on the little code you have shared I have created a canvas and filled it with a red square. When the button is pressed, an XHR query is generated to the same PHP with the POST method that sends the image encoded in BASE64.
PHP, when it detects the sending by POST of the field
imagen
, removes the initial header (up to the first comma) and decodes the BASE64 data to save it later in a file calledimagen.png
.The XHR code displays a link that allows you to view the image saved on the server. It is important that the server has write permissions on it for it to work.
Here is the example:
width
It is important to set the and attributesheight
of the canvas directly and not throughcss
them as they do not refer to the style, but to the size of the canvas<canvas>
. The image is sent to the server inBase64
.The path where the image is stored must have the necessary permissions.
I have commented the most important parts: