Javascript 3 - Moving the Rectangle
!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<canvas id="myCanvas" width = "600" height="400" style="border:1px solid"></canvas>
<script>
// set up canvas variable
var canvasVariable = document.getElementById("myCanvas");
var canvasVar = canvasVariable.getContext("2d");
// rectangle variables
var RectX = 10;
var RectY = 20;
var RectWidth = 40;
var RectHeight = 60;
// function for move right button
function btnMoveRight(){
RectX += 10;
render();
}
function render(){
// draw the rectangle
canvasVar.beginPath();
canvasVar.lineWidth= "5";
canvasVar.strokeStyle= "red";
canvasVar.rect(RectX, RectY, RectWidth, RectHeight);
canvasVar.stroke();
}
</script>
<br>
<button onclick="btnMoveRight()">Right</button>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<canvas id="myCanvas" width = "600" height="400" style="border:1px solid"></canvas>
<script>
// set up canvas variable
var canvasVariable = document.getElementById("myCanvas");
var canvasVar = canvasVariable.getContext("2d");
// rectangle variables
var RectX = 10;
var RectY = 20;
var RectWidth = 40;
var RectHeight = 60;
// function for move right button
function btnMoveRight(){
RectX += 10;
render();
}
function render(){
// draw the rectangle
canvasVar.beginPath();
canvasVar.lineWidth= "5";
canvasVar.strokeStyle= "red";
canvasVar.rect(RectX, RectY, RectWidth, RectHeight);
canvasVar.stroke();
}
</script>
<br>
<button onclick="btnMoveRight()">Right</button>
</body>
</html>
The button activates a function btnMoveRight() in the script. The btnMoveRight() changes the X value of the rectangle by adding 10 to the current value. Then it calls the render function to draw the rectangle with the new corrdinates.
1. Add buttons to move the rectangle left; up; and down.
1. Add buttons to move the rectangle left; up; and down.