【问题标题】:inserting image in html canvas code not working在html画布代码中插入图像不起作用
【发布时间】:2013-11-26 19:34:40
【问题描述】:

我正在尝试在画布中插入图像,但我的代码似乎不起作用。我得到了一个具有适当背景颜色的画布,但不知何故,图像没有显示出来。这是我的代码。 画布上的人物 .canvas1 { 背景颜色:灰色; 边框:1px 实心; }

</head>
<body>
    <div id="imagediv">
        <img id="spear1" src="E:\html-files\spear.png" style="height:150px; width:150px" draggable="true" ondrag="drag()" >
    </div>
    <div id="canvasdiv">
        <canvas id="mainCanvas" class="canvas1" height="500px" width="600px"></canvas>
    </div>

    <script>
        var canvas=document.getElementById("mainCanvas");
        var ctx=canvas.getContext("2d");
        var img=document.getElementById("spear1");
        ctx.drawImage(img,0,0,160,160);

    </script>
</body>

【问题讨论】:

标签: javascript html canvas


【解决方案1】:

如果要在画布中插入图像,则图像必须在插入之前已加载,因此您的代码可能如下所示:

var canvas=document.getElementById("mainCanvas");
var ctx=canvas.getContext("2d");
var img=document.getElementById("spear1");
img.onload = function(){
     ctx.drawImage(img,0,0,160,160);
}

【讨论】:

    【解决方案2】:

    尝试用相对路径链接图片,或直接链接到http://jsfiddle.net/combizs/5L7uL/

    这里是linking to a file stored online的例子

    <img id="spear1" src="http://jamesmcgillis.com/upload/google_logo_001_small.jpg"...
    

    如果它不适合你,请确保你的浏览器支持画布 :-)

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2022-01-13
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      相关资源
      最近更新 更多