Sometimes, we want to create a canvas 2d context without displaying the canvas with JavaScript.
In this article, we’ll look at how to create a canvas 2d context without displaying the canvas with JavaScript.
How to create a canvas 2d context without displaying the canvas with JavaScript?
To create a canvas 2d context without displaying the canvas with JavaScript, we can use the document.createElement method.
For instance, we write:
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 100;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#f00';
ctx.fillRect(20, 10, 80, 50);
const imgUrl = canvas.toDataURL();
const img = document.createElement('img');
img.src = imgUrl
document.body.appendChild(img)
to create the canvas with createElement.
Then we get the context with getContext.
Next, we set the fill style and add a rectangle with fillStyle and fillRect.
Then we convert the canvas to an image URL string with toDataURL.
Finally, we create an img element with createElement, set the src attribute to imgUrl and append the img element as a child of the body element with document.body.appendChild.
Now we should see a red rectangle displayed,
Conclusion
To create a canvas 2d context without displaying the canvas with JavaScript, we can use the document.createElement method.
