I want to apply gradient on canvas background. (Some text is written on canvas which is on Front) I added rect of same size on canvas & apply gradient on that rect.
var rect = new fabric.Rect({
left: 0,
top: 0,
width: canvas.width,
height: canvas.height,
selectable: false
});
canvas.add(rect);
canvas.sendToBack(rect);
rect.setGradient('fill',{
type: 'linear',
x1: 0,
y1: 0,
x2: rect.width,
y2: rect.height,
colorStops: {
0: $('#grdColor1').val(),
1: $('#grdColor2').val()
}
});
canvas.renderAll();
canvas.setActiveObject(text);
#grdColor1 & #grdColor1
are input fields which allow user to apply colors. This code is working fine. But i want to further change colors of ColorStops from input of colors. So user can select & change gradient colors dynamically afterwards too.
I tried this but its not working:
$("#grdColor1").on('change', function(){
o = canvas.item(0); //rect is set to back
o.colorStops({
0: $('#grdColor1').val(),
1: $('#grdColor2').val(),
});
canvas.renderAll();
});
Also tried rect.colorStops but no success .
Even further i want to change values of setGradient function "Linear" "Radial" "x1" "x2" etc. So user can dynamically set gradient options as per choice & colors.
What is the method to change the values of setGradient afterwards.
EDIT also tried :
$("#grdColor1").on('change', function() {
rect.setGradient('fill',{
colorStops: { //set colorStops again
0: $('#grdColor1').val(),
1: $('#grdColor2').val()
}
});
});
I think its not selecting the rect object since i send it to back and selected text object afterwards:
canvas.sendToBack(rect);
canvas.setActiveObject(text);
UPDATE 1 :
var r = canvas.item(0);
r.setGradient('fill',{
colorStops: {
0: $('#grdColor1').val(),
1: $('#grdColor2').val()
}
});
canvas.renderAll();
now rect is selecting but gradient is not applied properly. with this code rect background is changing to single color #grdColor1 only ie no gradient effect.
You need to change the setGradient on change of grdColor1
like,
$("#grdColor1").on('change', function(){;
rect.setGradient('fill',{
colorStops: { //set colorStops again
0: $('#grdColor1').val(),
1: $('#grdColor2').val()
}
});
canvas.renderAll(); // now render
});
Update try this,
var r = canvas.item(0);
r.setGradient('fill',{
type: 'linear',
x1: 0,
y1: 0,
x2: r.width,
y2: r.height,
colorStops: {
0: $('#grdColor1').val(),
1: $('#grdColor2').val()
}
});
canvas.renderAll();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.