HTML5 Development Notes: first glance at CANVAS, upload canvas images to the server,

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.