简体   繁体   English

背景图片JavaScript HTML5画布

[英]Background image javascript HTML5 canvas

I'm trying to create a simple game using javascript to run on a simple webpage. 我正在尝试使用javascript创建一个简单的游戏以在简单的网页上运行。 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><a href="index.html">Play Game</a></li>
<li><a href="about.html">About</a></li>
<li><a href="help.html">Help</a></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. 我相信您可能会在压缩加载之前尝试使用背景图片,但是您也可以将这些方法与CSS一起使用。

You can use CSS and either define in your style block or dynamically set it in JS. 您可以使用CSS并在样式块中定义或在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: 或者,如果更喜欢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. 如果使用JS,还请检查您的控制台是否有错误-JS在到达您的代码之前可能会因错误而中断。 Also for a working example see HTML5 Canvas background image 另请参见HTML5 Canvas背景图片作为工作示例

Try loading this in on onload event..and as suggested check console to see if there are any errors. 尝试在onload事件中加载它。并根据建议检查控制台,看是否有任何错误。

and what is bgImage ? 什么是bgImage bgImage.src = '/images/backGround.jpg'; ?

body.onload = RenderImage;
function RenderImage()
{
//Your existing script
}

Try to change bgImage to bkGround . 尝试将bgImage更改为bkGround And move setting src property after setting onload callback. 并在设置onload回调后移动设置src属性。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM