You can convert canvas to image and then send it via "raw"
To convert content to image, we need to access the toDataUrl of the canvas. It will serve to turn the object into a base64 .
By default, you will receive an image in PNG
, however, nothing image you can choose between JPEG
or WEBP
, for example.
Another thing you also need to keep in mind is that jQuery.ajax tries to convert the data to application/x-www-form-urlencoded
and we do not want this. We just want to send the content of the image. For this we should mark as false
, during the jQuery.ajax configuration.
Here is an example to aid 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 do not know the progress of the project, I will be brief in the back end part.
First, we must capture this POST RAW
. At PHP
we do this by passing the php://input
parameter to the file_get_contents
Then just use the str_replace function to replace the mime-type that is added when converting from canvas to base64
.
Once you've done this, you'll have your image to use in your project.
Follow the code to illustrate.
<?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));