简体   繁体   中英

I am not able to access input value on my canvas using JavaScript

I am not able to get the value of input statement in my JavaScript function, as i want my output on my canvas section of html but it is not showing anything on my canvas as well as in console.log function also. please help to solve this problem. thanks:)

 var x = document.getElementById("name").value; console.log(x); function myfunction() { var canvas = document.getElementById('page'); var ctx = canvas.getContext("2d"); ctx.font = "15px Arial"; ctx.fillText(x, 10, 50); }
 <:DOCTYPE html> <html> <head> <title>yoyo</title> </head> <body> <p>hi everyone;</p> <div> <label>Your text here-</label><br> <input type="text" name="name" id="name"> </div> <div> <canvas id="page" width="200" height="300" style="border: solid; background: yellow;"></canvas> <button onclick="myfunction()">click</button> </div> </body> </html>

The code below will get your input logged in the console. You need to have the console log inside of your myFunction function, so that the value of the input is only printed to console/checked once the user clicks the 'click' button. You should not create a variable requiring user input, and immediately try to access its value, because when the program is loaded the user has not input any value into the input yet. So below, your x variable is created by accessing the #id, the user fills in the input field, clicks the button, then the value of the x variable is checked, and printed to the console.

var x = document.getElementById("name");

function myfunction() {
  console.log(x.value);
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM