Share canvas on Facebook

I have a website where a user can design smartphones. At some point, the user should be able to share the design on Facebook, including the design. I have an object in the same way as the "style" defined as the URI of the canvas data.

Code for custom image sharing:

How can I share it with my image, since it is a data URI.

thanks

UPDATE : Now I have a canvas stored on the server, properly connected. Although, it seems, I can’t edit the "href" link on the Facebook link that is reading the thumbnail.

I tried:

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

and

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

No, it seems to work. The "fblink" object is correct, since I can read "rel", etc.

+4
source share
1 answer

I personally used canvas.toDataURL() , which generates the base64 encoded URL of your canvas content.

After that, I decoded the URL using the following Base64Binary.decode(encodedPng)

Once you have the decoded image, you can put it on the form and submit it all through the XMLHttpRequest object, as indicated in the code below:

  // 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 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 ); 

You can see the full working example of my Github project in maskToFb.html

+1
source

Source: https://habr.com/ru/post/1445783/


All Articles