Ввод текста в canvas
Без градиента текст выводится, но с градиентом его нет, не могу понять почему. И ещё, как можно сделать так, чтобы пользователь сам выбирал цвет текста?
<canvas id="canvas" width='600px'></canvas>
<input type="text" id="text"></input>
<button onclick="func();"> Ввод</button>
<input type="color" id="color">
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 5, 150, 220);
grd.addColorStop(0, "red");
grd.addColorStop(1, "purple");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 300, 200);
function func() {
var e = document.getElementById("text"),
t = document.getElementById("canvas"),
n = t.getContext("2d");
n.textBaseline = "top";
n.fillText(e.value, 150, 0);
}
</script>
Ответы (1 шт):
Автор решения: Николай Парахневич
→ Ссылка
Вы забыли указать цвет для текста.
Берем цвет из вашего поля ввода цвета, как:
colorText = document.getElementById("color"),
и перед "отрисовкой" текста указываем:
n.fillStyle = colorText.value;
Более подробно об fillStyle
Ваш пример:
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0, 5, 150, 220);
grd.addColorStop(0, "red");
grd.addColorStop(1, "purple");
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 300, 200);
function func() {
var e = document.getElementById("text"),
t = document.getElementById("canvas"),
colorText = document.getElementById("color"),
n = t.getContext("2d");
n.textBaseline = "top";
n.font = "30px serif";
n.fillStyle = colorText.value;
n.fillText(e.value, 50, 0);
}
func();
<canvas id="canvas" width='600px'></canvas>
<hr>
<input type="text" id="text" value="TestText"></input>
<button onclick="func();"> Ввод</button>
<input type="color" id="color">