使用Javascript将画布上传到服务器

时间:2018-02-15 11:18:16

标签: javascript canvas html5-canvas

我正在尝试裁剪图像并将其发送到服务器。

我的代码如下:

<div id="result">
     <img id="photo" src="http://localhost:63342/frontend/assets/images/audi.png?_ijt=hj4q47j1ghucndpqm4t9j0p08r"/>
     <canvas id="canvas"></canvas>
     <canvas id="crop-area" class="hide"></canvas>
</div>

在这种情况下,重要的是第二个画布<canvas id="crop-area" class="hide"></canvas>

当我完成选择(裁剪照片)后,我在上面的画布里面有一个rect,如下所示:

enter image description here

带有蓝色边框的是我要上传到服务器的裁剪部分。我尝试使用Html2Canvas,但该库获取div的屏幕截图,因此在我的情况下,它将所有内容上传到服务器,但我只想要蓝色部分,因此只有这个:

enter image description here

上传代码如下:

function renderMessage(wrapper, message){
    if(wrapper.classList.contains("fadeOut")) wrapper.classList.remove("fadeOut");
    if(wrapper.classList.contains("fadeIn")) wrapper.classList.remove("fadeIn");

    wrapper.classList.add("fadeIn");
    setTimeout(function(){
        wrapper.classList.add("fadeOut");
    }, 4000);
    wrapper.innerHTML = message;
    save_button_label.classList.remove('hide');
    save_button_spinner.classList.add('hide');
}

function upload_to_server(canvasData){

    return fetch(api_url, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({photo: canvasData})
    }).then(function (value) {
        if(value.ok){
            return value.json().then(function (response) {
                if(response.status === "success"){
                    drag = false;
                    buttons_shown = false;
                    selection_editing_buttons.classList.add("hide");
                    selection_editing_description.classList.remove("hide");
                    update = true;
                    rectangles = [];
                    return renderMessage(success, upload_success_msg);
                }else{
                    return renderMessage(errors, upload_error_msg);
                }
            })
        }
    }).catch(function (reason) {
        return renderMessage(errors, upload_error_msg);
    })

}

function onSaveChanges(){
    save_button_label.classList.add('hide');
    save_button_spinner.classList.remove('hide');

    console.log(crop_rect.startX); // I have start position x
    console.log(crop_rect.startY); // I have start position x
    console.log(crop_rect.w);      // I have width
    console.log(crop_rect.h);      // I have height

    html2canvas(document.getElementById("result")).then(function(canvas) {
        var canvasData = canvas.toDataURL("image/" + image_type + "");
        upload_to_server(canvasData)
    });
}

是否有可能获得裁剪的部分并将其上传到服务器。我有裁剪部分的start position xstart position y以及widthheight

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

Canvas toBlob polyfill (更好地寻找更好的选择):

if (!HTMLCanvasElement.prototype.toBlob) {
    Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
        value: function(callback, type, quality) {
            const binStr = atob(this.toDataURL(type, quality).split(",")[1]), len = binStr.length, arr = new Uint8Array(len);
            for (let i = 0; i < len; i++) arr[i] = binStr.charCodeAt(i);
            callback(new Blob([arr], { type: type || "image/png" }));
        }
    });
}

将画布上传到服务器:

croppedCanvas.toBlob((blob) => {
    formData.append("file", blob);
    fetch("/"  /* api_url in your case */, {
        method: "POST",
        body: formData
    }).then(r => r.json()).then(d => {
        //Your logic, in my case I get JSON from server
    });
}, "image/jpeg", 0.90);