我正在尝试将图像加载到画布上并且尝试所有内容后都没有工作...

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>


先谢谢您的帮助!

最佳答案

只要使用window.onload,您提供的代码就对我有用:

您是否将script代码包装在window.onload中?

<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>

关于javascript - 图片无法加载到 Canvas 上吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36779597/

10-13 01:44