Canvas drawImage不起作用,根本没有错误

时间:2014-12-17 08:20:17

标签: javascript image html5-canvas

这是代码

       function drawImg() {


                            var canvas = document.getElementById('mask');
                            var context = canvas.getContext('2d');

                            var img = new Image();
                            //alert(img.src);
                            img.src = "http://localhost/photo/webs.png";

                            img.onload = function(){

                                    context.drawImage(img, 100, 100);

                                    var URL = canvas.toDataURL();
                                    document.getElementById('main').src = URL;
                            };



                    }

和html代码是

         <img id="main" src="main.png" />
         <canvas class="mask" id="mask" width='200' height='200'></canvas>

         <p rel="32,223,95" onclick="drawImg()" title="Green">Green</p>

图像正在加载,已确认。但不分配给画布。

2 个答案:

答案 0 :(得分:0)

画布:

&#13;
&#13;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
&#13;
<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试使用:

<强>脚本:

   function drawImg() {
    var img = new Image();
    //alert(img.src);
    img.src = "home.png";
    console.log(img);
    if(img.complete) { //check if image was already loaded by the browser
           callback(img);
        }else {
           img.onload = callback;
        }


}
var callback = function(img) {

    var canvas = document.getElementById('mask');
    var context = canvas.getContext('2d');
    context.drawImage(img, 100, 100);
       var URL = canvas.toDataURL();
       console.log(URL);
       document.getElementById('main').src = img.src;
    }

<强> HTML:

<img id="main" src="main.png" />
         <canvas class="mask" id="mask" width='200' height='200'></canvas>

         <p rel="32,223,95" onclick="drawImg()" title="Green">Green</p>