Hello stackoverflow community,
I am working on a graphics engine in JavaScript, and currently am trying to repeat an image to use it as a background. Strangely, the initalize()
function is not being called, until directly called in the browser console. I before this, I had buttons to move the image which I am now trying to use as the background. Even then, the image would only appear after one of the buttons was pressed. (that old code is commented out). Here is the JavaScript:
var ctx;
var cam_x = 0,cam_y = 0;
//End of Global Variables
function initialize(){
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);//RESETS
var img=new Image();
img.src = "brick.png";
var i;
var j;
for(i = 0; i < 10; i++){
for(j = 0; j < 10; j++){
drawTile(img, i, j, 0);
}
}
console.log("should be drawing");
// drawTile(img, 0,0,0);
// drawTile(img, 1,0,0);
// drawTile(img, 2,0,0);
// drawTile(img, 1,1,0);
// drawTile(img, 2,2,0);
// console.log("should be drawing");
}
function setTransformations(){
ctx.translate(-cam_x,-cam_y);
}
function drawTile(img,x,y,z){
ctx.setTransform(1,0,-1,1,0,z);
setTransformations();
ctx.drawImage(img,x*32,y*32);
ctx.setTransform(1,0,0,1,0,0);
}
function camtranslate(x,y){
cam_x += x;
cam_y += y;
initialize();
}
The commented out drawTile()
calls were the to warp the image so it looked oblique (but that's not too relevant). Below is the HTML file:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #1ABC9C
}
</style>
<script src="main.js"></script>
</head>
<body>
<!-- <button onclick="camtranslate(16,0);"> Right </button>
<button onclick="camtranslate(-16,0);"> Left</button> <br>
<button onclick="camtranslate(0,-16);"> Up </button>
<button onclick="camtranslate(0,16);"> Down </button>
-->
<center>
<h1>Akimbo</h1>
<canvas id="canvas" height="600" width="600" style="border:1px solid #7F8C8D"></canvas>
</center>
<script>camtranslate(16, 0);</script>
</body>
</html>
The commented out buttons made the image appear on pressing them, but now that I've commented them out, even though I've called the function, it doesn't work. The HTML file should call the initialize()
function, but nothing appears in the canvas until I call the function directly in the console. How can I make it so that the background appears immediately upon the page's being loaded?
Thanks