0

Intento crear un texto en canvas pasandole el texto que usará el fillText() como parametro de la función desde un evento onclick en el documento HTML, pero me dice que la función crear() no esta definida.

window.addEventListener("load", function(){
/* Dibujo canvas */

var c = document.getElementById("m");
var ctx = c.getContext('2d');



function crear(texto) {
  
  ctx.fillText(texto,55,60);
  ctx.fillStyle = "#ECECF9";
}
  
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="text" id="e" placeHolder="Texto a dibujar.."/>
  <input type="button" value="Enviar" onclick="crear(document.getElementById('e').value)"/>
  <canvas width="100%" height="100%" id="m"></canvas>
</body>
</html>

2
  • Por que la funcion crear no existe a nivel de la página; la estas creando solo para load; mira bien las aperturas de inicio y cierre de tu código.
    – user34391
    el 10 jul. 2017 a las 23:58
  • 1
    El título no es descriptivo. No se incluye que es lo que esperas que haga el código. Véase ejemplo mínimo verificable.
    – Rubén
    el 11 jul. 2017 a las 0:06

3 respuestas 3

2

No anda porque la función cerrar está dentro de la función del evento "load". Una solución fácil es sacar la función como global o asignársela al objeto windows (que también la hace disponible globalmente).

Recomendación

Mantener separado el código del HTML (siempre que sea posible).

En tu caso significaría asignar el comportamiento del evento click desde el código Javascript (para eso hay que asignar un ID al botón).

window.addEventListener("load", function(){
    /* Dibujo canvas */

    var c = document.getElementById("m");
    var ctx = c.getContext('2d');

    //se define la función
    function crear(texto) {
        ctx.fillText(texto,55,60);
        ctx.fillStyle = "#ECECF9";
    }
    // se asigna la función al botón
    document.getElementById('el-boton').addEventListener('click',function(){ 
        crear(document.getElementById('e').value);
    });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="text" id="e" placeHolder="Texto a dibujar.."/>
  <input type="button" value="Enviar" id="el-boton"/>
  <canvas width="100%" height="100%" id="m"></canvas>
</body>
</html>

Ventajas:

  1. El HTML viaja sin código (es más seguro)
  2. No hay necesidad de poner globales las funciones (y el código queda más ordenado)
0

onclick espera que la funcion este en ambito global pero tu lo tienes en ambito local del evento window.addEventListener("load", function(){})

Intenta haciendo la funcion visible globalmente con window:

window.addEventListener("load", function(){
/* Dibujo canvas */

var c = document.getElementById("m");
var ctx = c.getContext('2d');



window.crear = function (texto) {
  
  ctx.fillText(texto,55,60);
  ctx.fillStyle = "#ECECF9";
}
  
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="text" id="e" placeHolder="Texto a dibujar.."/>
  <input type="button" value="Enviar" onclick="crear(document.getElementById('e').value)"/>
  <canvas width="100%" height="100%" id="m"></canvas>
</body>
</html>

0

Es más fácil si divides un poco las tareas.

var c = document.getElementById("m");
var ctx = c.getContext('2d');
var texto;

function escribir(texto) {
  ctx.fillText(texto,55,60);
  ctx.fillStyle = "#ECECF9";
}

function getText() {
    var texto = document.getElementById('e').value;
    escribir(texto);
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="text" id="e" placeHolder="Texto a dibujar.."/>
  <input type="button" value="Enviar" onclick='getText()'/>
  <canvas width="100%" height="100%" id="m"></canvas>
</body>
</html>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.