Bonsai: How can user save the memes?


#1

Hello! I just completed the Bonsai project. I was wondering, how would one go about in order to give the user the option to save their meme? What code can be used? Thanks in advance!


#2

Hey Mark,

To the best of my knowledge, there's currently no way to save the meme without having the user manually screenshot it, which definitely isn't the ideal way to do it.
If you're interested, it could be done using the HTML5 <canvas>, though - please let me know if you have any questions about that :)


#3

Thanks for the reply.
That's too bad.
How would I use in this situation?


#4

Once you get your basic canvas set up, see: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text to draw text. I don't think drawing text will be too hard, but let me know if you need help with that :)
To save the meme, I think you'd get your code looking like this:

<!-- html -->
<!-- other stuff -->
<button id="save">Save meme</button>

<canvas id="c">Sorry, &lt;canvas&gt; doesn't seem to be supported</canvas>
          <!-- ↑ this will get shown if the stuff in the canvas can't be -->
<!-- other stuff -->

// javascript
var canvas = document.querySelector('#c'),
    ctx = canvas.getContext("2d"),
    saveButton = document.querySelector('#save');

// this is the magic function
// it's only been copy/pasted, so there may be 
// parts specific to the original thing here: 
// http://codepen.io/zystvan/pen/JoJVME
function savePicture() {
    var canvas2 = document.createElement("canvas"); // create a temporary canvas
    var ctx2 = canvas2.getContext("2d"); // get its context
    canvas2.width = canvas.width; // set its width
    canvas2.height = canvas.height; // set its height

    ctx2.drawImage(canvas, 0, 0); // draw the main canvas onto it

    ctx.fillStyle = canvas.style.backgroundColor; // set the fillStyle to the CSS color
    ctx.fillRect(0, 0, canvas.width, canvas.height); // fill the main canvas that color
    ctx.fillStyle = theColor; // set the fillStyle back to what it was

    ctx.drawImage(canvas2, 0, 0); // draw the temporary canvas on top of the main one

    window.open(canvas.toDataURL()); // convert to image and open a window

    ctx.clearRect(0, 0, canvas.width, canvas.height); // clear main canvas
    ctx.drawImage(canvas2, 0, 0); // put original image back on main canvas
}

saveButton.onclick(savePicture()) // not tested; i think this'll work, though

I think that code will mostly work. I haven't tested it yet though, because it's getting late and as a human, I need sleep. I'll try to get around to testing it tomorrow morning, or you can work on it yourself :)


#5

best written as,

... &lt;canvas&gt; ...

?


#6

Thanks for all this info.
I'm gonna have to study this to understand better.
Thanks a million for all of your help!