0

I want to be able to replicate something like this: https://via.placeholder.com/150

I have some data that I'd like to put in a URL and have the response be an image. I'm using javascript to get parameters passed in the url and then build an HTML canvas. I want to be able to convert that canvas to an image and send that back as the response.

/**
 *    Gets URL params
*/
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,                     function(m,key,value) {
    vars[key] = value;
});
return vars;
}

var fullName = decodeURIComponent(getUrlVars()["fullName"]);

var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');

function doCanvas() {
    /* draw something */
    ctx.fillStyle = '#f7f7f7';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#4b4f54';
    ctx.font = '12px sans-serif';
    ctx.fillText("Name: "+fullName, 10, 18);
}

/**
 * Draw something to canvas
 */
doCanvas();

The canvas works great and the data I passed in through the URL gets displayed. I still need help figuring out how to convert this canvas to an image and send that to the visitor of the URL rather than the page containing the canvas.

I appreciate any ideas on how I might accomplish this. Thank you!

  • Possible duplicate of: https://stackoverflow.com/questions/923885/capture-html-canvas-as-gif-jpg-png-pdf – Ben Dec 27 '18 at 22:27
  • 1
    Possible duplicate of [Capture HTML Canvas as gif/jpg/png/pdf?](https://stackoverflow.com/questions/923885/capture-html-canvas-as-gif-jpg-png-pdf) – nircraft Dec 27 '18 at 22:32

1 Answers1

0

You can use the toDataURL method on the canvas element to create an image from the canvas. You'll then be able to send this image to which ever backend you're working with.

Example HTML

<canvas id="mycanvas">
<form action="SERVER_ROUTE_HERE" method="post" id="submit-canvas-form">
  <input type="hidden" name="canvas" id="canvas-image">
  <button>Submit Drawing</button>
</form>

JS

let mycanvas = document.getElementById("mycanvas");
let form = document.getElementById("submit-canvas-form");
let cvImage = document.getElementById("canvas-image");

form.onsubmit = (event) => {
    event.preventDefault();
    let image = mycanvas.toDataURL("image/png");
    cvImage.value = image;
    form.submit();
}