2016-04-21 49 views
0

我试图将图像加载到画布上,并试图一切后,一直没有工作......图像不载入画布上?

的Javascript:

var canvas = document.getElementById('myCanvas'); 
var context = canvas.getContext('2d'); 
var start = new Image(); 

start.onload = function(){ 
    context.drawImage(start, 0, 0, start.width, start.height, 0, 0, 
    canvas.width, canvas.height); 
    } 

start.src = "hangman0.png"; 

我看不出有什么毛病我的代码,我想得出这样的图像,然后规模为画布的宽度和高度,但画面只是没有显示出来,不管是什么。任何指针?我试过改变我的HTML5和CSS代码,仍然无济于事。

CSS:

canvas{ 
    background-color: rgb(0,198,255); 
    border-style: ridge; 
    border-width: 5px; 
    border-color: rgb(157,255,0); 
    position: relative; 
} 

HTML5:提前为帮助

<body> 
    <div id='section'> 
     <canvas id='myCanvas' width='979px' height='560px'></canvas> 
     <script src="projectJavaScript.js"></script> 
    </div> 
</body> 

谢谢!

回答

-1

你似乎是设置图像源是使用将被它会使用默认的空白状态,当它被调用后。

也出现使用start.onload是开始,但不表示一个元素,但varble,它不会因为原来的HTML元素的它不属于被加载。我会用canvas.onload或body.onload运行

1

你提供的代码工作对我来说,只要我使用window.onload

你包裹里window.onloadscript代码?

<script> 
window.onload=(function(){ 

    var canvas = document.getElementById('myCanvas'); 
    var context = canvas.getContext('2d'); 
    var start = new Image(); 

    start.onload = function(){ 
     context.drawImage(start, 0, 0, start.width, start.height, 0, 0, 
     canvas.width, canvas.height); 
     } 

    start.src = "https://dl.dropboxusercontent.com/u/139992952/multple/rainy.png"; 

}); // end window.onload 
</script> 

实施例的代码和一个演示:

注:StackSnippets自动换JS-脚本代码内的window.onload

var canvas = document.getElementById('myCanvas'); 
 
var context = canvas.getContext('2d'); 
 
var start = new Image(); 
 

 
start.onload = function(){ 
 
    context.drawImage(start, 0, 0, start.width, start.height, 0, 0, 
 
    canvas.width, canvas.height); 
 
    } 
 

 
start.src = "https://dl.dropboxusercontent.com/u/139992952/multple/rainy.png";
body{ background-color: ivory; } 
 
canvas{border:1px solid red; margin:0 auto; }
<canvas id='myCanvas' width='979px' height='560px'></canvas>

+0

对不起,我对于一些JS术语来说这不太好,因为我相当新s,你通过在window.onload中包装脚本代码是什么意思?我的JavaScript代码在它自己的文件中,我从HTML文件中调用脚本。我也试过你的代码,仍然没有画任何东西:( –

+0

“包装”手段把你的代码里面的东西 - 在这种情况下,它意味着把你的代码在函数内部['函数(){YOUR-CODE}']那对于浏览器等待它试图执行你的JS之前加载窗口所以,在外部JS文件,把'在window.onload =(函数(){'在顶部和'})'底部: - ) – markE

+1

我现在做的包装,但它有点毛刺我的整个页面,现在,它的绘图我想要的图片,但持续闪烁整个页面白色,和我的网页无法完成加载,即加载循环继续运行。但至少它与之前相比完全没有改变,非常感谢!我会尽量先解决这个问题。 –