Collaborative Drawing App: Clearing and Downloading the Canvas Image

Shawn
2 min readMay 28, 2022

--

In this section we set up the ability to clear and download the image.

Clearing the Image

Clearing the image is simple a matter of drawing a white square over the whole canvas. Here’s the button, which goes under the shape buttons.

<div>
<button onclick="canvas.clear()">Clear</button>
</div>

And here’s the method to add to the Canvas class:

clear() {
this.ctx.clearRect(0, 0, 500, 500);
}

Downloading the Image

Downloading the drawn image is also simple to implement, but can be confusing to understand. Add the HTML right under the Clear button, in the same <div> as above:

<button onclick="canvas.download()">Download</Button>

And the method:

download() {
const image = this.canvas.toDataURL('image/png', 1.0);
image.replace('image/png', 'image/octet-stream');
const link = document.createElement('a');
link.download = 'canvas-image.png';
link.href = image;
link.click();
}

Have you ever opened an image in a new tab, and in the URL bar it said “data:image/png;base64” followed by a long string of numbers and letters? That’s what toDataURL generates. So the first two lines convert the canvas drawing into something downloadable. The rest of the function creates an <a> tag that we programmatically click to trigger a download.

Putting it Together

Since this is a short section, I suspect you can figure out where the code is supposed to be. We’ll finish with a screenshot of what the app should look like at this point, and pick up in next section with a start on socket work.

Clear and Download added

Collaborative Drawing App Series

--

--