So what I’m trying to do here is to pass information from a input form of number type to javascript and then re-draw the canvas with the updated variable data.
Here’s what I’ve got so far:
<!DOCTYPE HTML>
<html>
<head>
<script language = "JavaScript">
var canvas;
var context;
var _x = 0;
function draw(newx) {
context.rect(newx,100,100,100)
context.strokeStyle = "red"
context.stroke()
}
function sendVal(form) {
_x = form.xx.value;
context.clearRect(0,0,canvas.width,canvas.height);
draw(_x);
}
window.onload = function() {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
context.rect(_x,100,100,100);
context.strokeStyle = "blue";
context.stroke();
};
</script>
</head>
<body>
<FORM NAME="SENDX" ACTION="" METHOD="GET">
Enter X: <INPUT TYPE="number" NAME="xx">
<INPUT TYPE="submit" VALUE="ENTER CO-ORDINATES" onClick="sendVal(this.form)">
</FORM>
<canvas id="myCanvas" width="500" height="500"></canvas>
</body>
</html>
As you can see above, I’ve tried making the canvas’s context variable public so that I can access its functions from another part of the javascript, but the canvas never updates itself. How do I fix this? Thanks.
I think your problem is not in the JavaScript but the HTML, an input of type “submit” wants to cause a form submit event, you just want an onclick event. Try just using:
Working JSFiddle: http://jsfiddle.net/nwellcome/mJyps/5/