You can convert canvas to image and then send via "raw"
To convert the content to image, we need to access the function toDataUrl canvas. It will serve to transform the object into a Base64.
By default, you will receive an image in PNG
, however, nothing picture you can choose between JPEG
or WEBP
, for example.
Another that you also need to keep in mind, is that by default, the jQuery.ajax tries to convert the data to application/x-www-form-urlencoded
and we don’t want that. We just want to upload the contents of the image. For that we must mark as false
, during jQuery.ajax configuration.
Here is an example to help understanding.
Front-end:
<h1 id="welcome">Hello Brazil!</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js" type="text/javascript"></script>
<script>
html2canvas( [ document.body ], {
onrendered: function( canvas ) {
$.ajax({
url: 'index2.php',
type: 'POST',
data: canvas.toDataURL(), // Captura a imagem em base64
contentType: 'image/png', // Informa o mime-type da imagem que por padrão é PNG
processData: false //Informa ao jQuery.ajax para não converter os dados em application/x-www-form-urlencoded
});
}
});
</script>
Back-end:
As I don’t know the progress of the project, I will be brief in the back-end part.
First, we must capture this POST RAW
. In the PHP
we do this by passing the parameter php://input
in function file_get_contents
Then just use the function str_replace to replace the mime-type that is added when converting from canvas to base64
.
Done this, you will have your image to use in your project.
Follows code to exemplify.
<?php
$imageEncoded = str_replace("data:image/png;base64,", "", file_get_contents("php://input"));
$imageDecoded = base64_decode($imageEncoded);
// Salva a imagem
file_put_contents("image_screenshot.png", print_r($imageDecoded, true));