I am trying to create a canvas object which I can use to create an image from (using canvas.toDataURL()
).
One of the key elements of this canvas, has to be the background gradient set using the following css:
background: -webkit-linear-gradient(-45deg, #1e5799 0%,#2989d8 36%,#207cca 71%,#7db9e8 100%);
.
As you can see this is set using a certain angle (-45deg)
.
Is there any way for me to create this using canvas and also being able to create an image from this which includes this background?
This doesn't work when manually setting the css-background property, as toDataURL
does not take into account any css. I have also looked at drawing it into the canvas myself, but ctx.createLinearGradient
does not support drawing of angles.
How can I achieve a canvas which allows toDataURL
which includes my desired background?
I am trying to create a canvas object which I can use to create an image from (using canvas.toDataURL()
).
One of the key elements of this canvas, has to be the background gradient set using the following css:
background: -webkit-linear-gradient(-45deg, #1e5799 0%,#2989d8 36%,#207cca 71%,#7db9e8 100%);
.
As you can see this is set using a certain angle (-45deg)
.
Is there any way for me to create this using canvas and also being able to create an image from this which includes this background?
This doesn't work when manually setting the css-background property, as toDataURL
does not take into account any css. I have also looked at drawing it into the canvas myself, but ctx.createLinearGradient
does not support drawing of angles.
How can I achieve a canvas which allows toDataURL
which includes my desired background?
1 Answer
Reset to default 9Grabbing the background of the canvas element will not work as it is not part of the canvas bitmap (2D context in this case).
You have to use the createLinearGradient
for that. As you say, it does not support an angle directly, but creates a gradient using a line (x1,y1)-(x2,y2).
This means we can use a little trigonometry to produce the angle we want.
If you want to create a line at an angle just do:
var x2 = length * Math.cos(angle); // angle in radians
var y2 = length * Math.sin(angle); // angle in radians
Now you can use this with createLinearGradient
:
var gr = ctx.createLinearGradient(0, 0, x2, y2);
Example
var ctx = document.querySelector("canvas").getContext("2d"),
angle = 45 * Math.PI / 180,
x2 = 300 * Math.cos(angle),
y2 = 300 * Math.sin(angle),
gr = ctx.createLinearGradient(0, 0, x2, y2);
gr.addColorStop(0, "black");
gr.addColorStop(1, "blue");
ctx.fillStyle = gr;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
var uri = ctx.canvas.toDataURL();
console.log(uri);
<canvas></canvas>