在Facebook上分享画布

时间:2012-11-13 14:21:50

标签: javascript html facebook html5 canvas

我有一个用户可以设计智能手机外壳的网站。用户应该能够在Facebook上共享设计,包括设计。我有对象和a,将'style'设置为画布的数据URI。

分享时自定义图片的代码是:

我如何与我的图片分享,因为它是一个数据URI。

由于

更新: 我现在将画布保存在服务器上,正确链接。虽然,我似乎无法编辑链接的“href”Facebook从中读取缩略图。

我试过了:

var fblink = document.getElementById(“facebook_share”); fblink.href = “http://example.com/image.png”;

fblink.setAttribute(“href”,“http://example.com/image.png”);

似乎无效。 'fblink'对象是正确的,因为我可以阅读'rel'等。

1 个答案:

答案 0 :(得分:1)

我个人使用canvas.toDataURL()生成画布内容的base64编码网址。

之后,我使用以下命令Base64Binary.decode(encodedPng)

解码了URL

获得解码后的图像后,您可以将其放入表单中,并通过以下代码中指定的XMLHttpRequest对象发送所有内容:

            // Random boundary defined to separate element in form
            var boundary = '----ThisIsTheBoundary1234567890';

            // this is the multipart/form-data boundary we'll use
            var formData = '--' + boundary + '\r\n';
            formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
            formData += 'Content-Type: ' + mimeType + '\r\n\r\n';

            // let's encode our image file
            for ( var i = 0; i < imageData.length; ++i ) {
                formData += String.fromCharCode( imageData[ i ] & 0xff );
            }

            formData += '\r\n';
            formData += '--' + boundary + '\r\n';
            formData += 'Content-Disposition: form-data; name="message"\r\nContent-Type: text/html; charset=utf-8\r\n\r\n';
            formData += message + '\r\n'
            formData += '--' + boundary + '--\r\n';

            // Create a POST XML Http Request
            var xhr = new XMLHttpRequest();
            xhr.open( 'POST', 'https://graph.facebook.com/me/photos?access_token=' + authToken, true );
            // Call back function if POST request succeed or fail
            xhr.onload = xhr.onerror = function() {
                if ( !(xhr.responseText.split('"')[1] == "error") ) {
                    // If there is no error we redirect the user to the FB post she/he just created
                    var userID = xhr.responseText.split('"')[7].split('_')[0];
                    var postID = xhr.responseText.split('"')[7].split('_')[1];
                    w = window.open('https://www.facebook.com/'+userID+'/posts/'+postID,
                            'width=1235,height=530');
                }
                else {
                    alert("Erreur: "+xhr.responseText);
                }
            };
            xhr.setRequestHeader( "Content-Type", "multipart/form-data; boundary=" + boundary );

            // Attach the data to the request as binary
            xhr.sendAsBinary( formData );

您可以在文件maskToFb.html中找到Github project上的完整工作示例