I'm trying to create a simple game using javascript to run on a simple webpage. For some reason, I can't get it to load a background image. I've searched repeatedly and tried numerous ways but I ended up with a black-white canvas. Please, help me as I'm at my wits end.
Here's my code snippet:
<body>
<!-- Site navigation menu -->
<ul>
<li>Play Game</li>
<li>About</li>
<li>Help</li>
</ul>
<!-- Creating the canvas -->
<canvas id= "gameCanvas" width="600" height="480"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var bkGround = new Image();
bgImage.src = '/images/backGround.jpg';
bkGround.onload = function(){
ctx.drawImage(bkGround,69,50);
}
</script>
Anticipated thanks.
I believe that you may be trying to use the background image before has complted loading but you can also use these approaches with CSS.
You can use CSS and either define in your style block or dynamically set it in JS.
<style>
#gameCanvas{
background-image: url(/images/backGround.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
</style>
or if prefer in JS:
document.getElementById("gameCanvas").style.background = "url('/images/backGround.jpg')";
NB - make sure the image is access to the browser.
Also check your console for errors if using JS - the JS may be breaking with an error before reaching your code.
Also for a working example see HTML5 Canvas background image
Try loading this in on onload event..and as suggested check console to see if there are any errors.
and what is bgImage ? bgImage.src = '/images/backGround.jpg'; ?
body.onload = RenderImage;
function RenderImage()
{
//Your existing script
}
Try to change bgImage to bkGround. And move setting src property after setting onload callback.
So your code will be:
<canvas id= "gameCanvas" width="600" height="480"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var bkGround = new Image();
bkGround.onload = function(){
ctx.drawImage(bkGround,69,50);
};
bkGround.src = '/images/backGround.jpg';
</script>
Related
I am currently working on a small Web App Game written angular. I wanted to add a feature for users to draw their on profile picture using a canvas HTML element.
I never worked with canvas before so i searched the internet for examples and i found this one which really helped me out getting started.
So i created a component and used exactly this code which worked immediately. My next goal was to make the canvas size responsive, so it looks good on every device.
A quick google search gave me multiple ways to achive this:
Adding width: 100%; height: 100% to the canvas style
Setting the size in ngAfterViewInit() like this:
canvasEl.style.width = "100%";
canvasEl.style.height = "100%";
canvasEl.width = canvasEl.offsetWidth;
canvasEl.height = canvasEl.offsetHeight;
Both solution kind of worked. The canvas was now as big as possible which was great.
However the drawing did not work properly anymore.
When drawing the canvas wasn't changing at all or the lines were not created at the position of the cursor (instead of increased canvas size it felt like the canvas was stretched and the actual size in pixel did not change).
As CBroe mentioned i have to set the width and height of the properties of the canvas itself.
So now i am trying to retrieve the height and width of the parent container in ngAfterViewInit() but the values are always zero:
#ViewChild('parent') parent: ElementRef;
ngAfterViewInit() {
...
console.log (this.parent.nativeElement.offsetHeight);
...
}
html code:
<div #parent fxFlex>
<canvas id="responsive-canvas" #myCanvas></canvas>
</div>
After a lot of try and error i found a solution to my problem which looks like that:
replaced the height and width set in the ngAfterViewInit() of the canvas with this code
canvasEl.style.width = "100%";
canvasEl.style.height = "100%";
canvasEl.width = canvasEl.offsetWidth;
canvasEl.height = canvasEl.offsetHeight;
and this is what my html code looks like:
<div #parent fxFlex style="height: 200px;">
<canvas
id="responsive-canvas"
[height]="parent.offsetHeight"
[width]="parent.offsetWidth"
#myCanvas
>
</canvas>
</div>
It is important, that the height of the parent is set. Otherwise it does not work.
I have this code for a canvas and a chat:
<section id="main_section">
<article id="GL">
<canvas id="GL-Surface">
</canvas>
</article>
<article id="chat">
<script src="chat.js"></script>
</article>
</section>
I want to set the width and height of the chat. It works when setting it in CSS, but I want to change the size of the chat inside of Javascript, since the canvas might get bigger. I use these commands to set the size:
document.getElementById("chat").width = w;
document.getElementById("chat").height = h;
But the chat doesn't change the size. These lines work for changing the size of the article containing the canvas. Printing out the document.getElementById("chat").width returns the right value, which is weird.
What is going on, that the same commands only work for some objects?
Since you have set the width and height in your CSS, you can only modify the style properties of the canvas to change it, i.e. canvas.style.width and canvas.style.height.
const canvas = document.querySelector('canvas');
canvas.style.width = "500px";
canvas {
width: 200px;
height: 200px;
background-color: dodgerblue;
}
<canvas></canvas>
The <script> tag doesn't belong there - it may know what the #gl element is, but it may not know what #chat is if the script executes before #chat gets defined by closing the article tag.
Move it to the bottom of the body.
This is really for informational and learning purposes while learning more about JavaScript and CSS. I have a local browser index page that I wanted to rotate the background image onload. After looking around and playing with different solutions, I settled on this for the basic rotate functionality:
<html>
<head>
<script language="javascript" type="text/javascript">
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
document.body.style.background = "url(" + img + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
</script>
</head>
<body onload="rotate()">
</body>
</html>
During the process, before I just set the backgroundSizeas cover to fill the window, I was playing with the idea of resizing the images before setting them as the background image after they are selected from the array.
I have done a lot of searching, and the only real working solutions I have found rely on selecting the element by ID, but that also requires that the image has an ID associated, such as in the IMG property in the HTML code. Here the image is selected and set in the JavaScript with CSS.
I have tried setting the image dimensions with img.width / img.height and img.style.width / img.style.height, as well as a few other random solutions I have come across, but whenever I try to change these the image either does not change or it does not show at all.
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
image = rsize(img);
document.body.style.background = "url(" + image + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
function rsize(image)
{
image.style.width = "300px";
image.style.height = "300px";
return image;
}
I know I am probably doing something wrong here. Is there a way, in this circumstance, that I can resize these images? Or is there a better way to construct this?
Thanks in advance.
You must set image.style.width and image.style.height on an actual image DOM object, not on the URL as you are currently trying to do.
As an image object is not used for background images, you can't really directly do what you're trying to do for a background image.
You could use the CSS background-size property, but that is fairly new and is not supported in versions of IE prior to IE9. If you were using that, you would set the actual size for that, not "cover".
You could also use an actual DOM image and then present that DOM image as centered in your page if that's what you're really trying to do.
For example, here's how you create a DOM image object, assign it a URL, set it's size and insert it into your page:
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var imgURL = imgArray[aImg];
var img = new Image();
img.src = imgURL;
img.style.width = "300px";
img.style.height = "300px";
img.id = "centeredImage";
document.body.appendChild(img);
You could then use CSS to position is in the center of your page if you wanted.
Working demo here: http://jsfiddle.net/jfriend00/jqMtV/
No, you have no <img> elements you could (re)size (btw, they would not need ids to be selectable). Your use of rsize(imgArray[aImg]) operates on the array members, which are strings and not DOM elements, so setting values on their non-existent style property would throw an error.
Yet, you're already on the right way with using the backgroundSize style property. Just don't set it to cover, but to the size you need!
document.body.style.backgroundSize = "300px 300px";
If you would want to use a <img> element, add this at the end of your <body>:
<img src="some.jpg" style="position:fixed; z-index:-1; width:100%; height:100%" />
is possible to get background image width which is defined in CSS?
body {
background-image: url('background.jpg');
}
I need something like this:
window.getComputedStyle(document.body, 'background-width');
var u = window.getComputedStyle(document.body, 'background-image');
u = u.replace(/url\(/, '').replace(/\)/, '');
var w = 0;
var i = new Image();
i.onload = function( ){ w = this.width; alert(w); }
i.src = u;
warning: i have ommitted a case, when body has no background image specified, keep that in mind.
is possible to get background image width which is defined in CSS?
I don't think so, but you should be able to use a little trick : Load the image into an img element as described in this question.
If you do this after the document has been fully loaded, the browser should fetch the image from the cache.
It's impossible to do this directly without some sort of work around.
Use JQuery to detect what image the background has, with the imagesLoaded (recommended) or onImagesLoad plugin.
Use the JQuery Dimensions plugin to get the image size.
when I dynamically add an image to a div the image doesn't scale when you resize the window in Internet Explorer.
I think it's more clear if I show two really simple examples:
The following example doesn't use JavaScript it's just plain html and it does what I want.
http://www.friendly-stranger.com/halp/ie-width/index.html
The next one uses JavaScript and if you resize the width of your browser window the image doesn't scale only the width gets smaller.
http://www.friendly-stranger.com/halp/ie-width/bad.html
This is a screenshot of both examples:
(source: friendly-stranger.com)
The JavaScript code I use:
<script type="text/javascript">
$(function(){
var img = new Image();
img.src = 'Koala.jpg';
$('div').append(img);
});
</script>
<script type="text/javascript">
$(function(){
var img = new Image();
img.src = 'Koala.jpg';
img.style.height = 'auto';
$('div').append(img);
});
</script>
try this, i hope it'll work