Can I do server side processing of canvas using PHP

Viewed 136

I am creating a larger file with different pattern on canvas. Assuming the file size is 20,000 x 20,000 px. This is too much processing to be done on client side so I need to create the canvas and then make png from it which is then given as a download file.

The question is, Is there any way to do server side processing on <canvas> element in PHP. There is a node package called "canvas" but I am looking for something in PHP?

1 Answers

You'd have to convert your canvas to a Blob or a base64 string anyway if you want to send it to a server... and then process that on the server too and return it to the client. It really feels like unnecessary extra steps that hurt you more than they help you.

What I'd personally do in this scenario is convert the canvas to a Blob, create a stream from that Blob, and use StreamSaver.js to save it in a memory-efficient way. Does it improve processing time? No, but it's definitely better in terms of RAM usage. You could display a message to the user while it's generating.

function saveImage() {
  message.innerText = 'Generating image...';
  const start = performance.now();
  const blob = canvas.toBlob(async function (blob) {
    const fileStream = streamSaver.createWriteStream('test.png');

    const readableStream = blob.stream();
    await readableStream.pipeTo(fileStream);

    const end = performance.now();
    console.log(end - start);

    message.innerText = 'Done!';
  });
}

Fiddle for full example: https://jsfiddle.net/gp2xtbkn/

Related