HTML5 Development Notes: first glance at CANVAS, upload canvas images to the server,
The project provides the image cropping function, which allows users to crop an image when uploading it, and select an appropriate size position as the Avatar. The crop. js plug-in is used, and canvas is used to directly draw the cropped and scaled image. The cropping process is not detailed here. If you want to learn more, you can take a closer look at crop. js plug-in. Here we will share a process of uploading the canvas image to the server through ajax after it is generated. Take PHP as an example:
<script>var canvas = document.getElementById("canvas_img");var img = canvas.toDataURL();var ajax = null; if (window.XMLHttpRequest) { ajax = new XMLHttpRequest();} else { ajax = new ActiveXObject("Microsoft.XMLHTTP");}ajax.onreadystatechange = function() { if (ajax.readyState == 4 && ajax.status == 200) { alert(ajax.responseText); }}ajax.open("POST", "save.php", true);ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");ajax.send("img=" + img);</script>
<? Php define ('upload _ dir', dirname (_ FILE __). '/'); // image storage path $ img =$ _ POST ['img ']; $ img = str_replace ('data: image/png; base64 ,', '', $ img); $ img = str_replace ('', '+', $ img); $ data = base64_decode ($ img ); $ day = date ("Ymd", time (); $ file_name = mt_rand (000000000000000,999999999999999999); if (! Is_dir (UPLOAD_DIR. $ day) {mkdir (UPLOAD_DIR. $ day) ;}$ file = UPLOAD_DIR. $ day. "/". $ file_name. '.png '; $ success = file_put_contents ($ file, $ data); return $ success;?>
Through ajax transmission, the server receives the content of the entire image file and writes it into the file. This gives the so-called 'upload image' effect.