I have created a program that can move a rectangular block up, down, right, and left within a canvas using the w, a, s, and d keys. There is an error when setting a variable to represent the width of the canvas. The error comes up for this line of code:
var cw=canvas.width;
I have been trying to use this code on Chrome. Here is the full code:
<html>
<head>
<script>
var positionX=0;
var positionY=0;
var cw=canvas.width;
var ch=canvas.height;
var canvas=document.getElementById("canvas1");
window.addEventListener("keydown", onKeyPress, true);
function draw(){
var canvas=document.getElementById("canvas1");
var cw=canvas1.width;
var ch=canvas1.height;
var context=canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle="green";
context.fillRect(positionX, positionY, 100, 100);
context.strokeStyle = 'black';
context.stroke();
}
function onKeyPress(e){
if (e.keyCode==87){
positionY=Math.max(0,positionY-15);
}
if (e.keyCode==83){
positionY=Math.min(cw-500,positionY+15);
}
if (e.keyCode==68){
positionX=Math.min(ch-500,positionX+50);
}
if (e.keyCode==65){
positionX=Math.max(0,positionX-50);
}
draw();
}
</script>
</head>
<body>
<div id="firstDiv">
<canvas id="canvas1" width="500" height="500" style="border: 1px solid black;"> </canvas>
</div>
</body>
</html>
canvas1defined ?