如何使用图像DOM元素作为jCanvas中source属性的值?

时间:2012-06-02 22:54:04

标签: javascript jquery jcanvas

我想测试一下这个例子:http://calebevans.me/projects/jcanvas/sandbox.php#%24%28%22canvas%22%29.drawImage%28%7B%0A%20%20source%3A%20%24%28%27%23image-fish%27%29%5B0%5D%2C%0A%20%20x%3A%2050%2C%20y%3A%2050%2C%0A%20%20width%3A%20100%2C%0A%20%20fromCenter%3A%20false%0A%7D%29%3B

但是我没有在浏览器中看到任何结果,默认情况下为“img src”。请有人帮助我。我该如何使用这个功能?

  <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Demo</title> 
        <canvas width="500" height="250"></canvas> 
      </head>
        <script src="jquery.js"></script>
        <script src="jcanvas.js"></script>
        <script>

        $("canvas").drawImage({
        source: $('#draggable')[0],
        x: 50, y: 50,
        width: 60,
        fromCenter: false
        });

        </script>            
         <body>
            <img src="../image/0.jpg" class="drag-image" id="draggable"/>
        </div>
      </body>
    </html>

感谢。

1 个答案:

答案 0 :(得分:2)

设置canvas标记的source时,

图像标记未完全加载。结果,$('#draggable')[0]返回undefined。尝试在加载文档时调用drawImage。 以下内容应该可以解决您的问题。

 <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Demo</title> 
        <canvas width="500" height="250"></canvas> 
      </head>
        <script src="jquery.js"></script>
        <script src="jcanvas.js"></script>
        <script>

        $(document).ready(function(){
            $("canvas").drawImage({
                 source: $('#draggable')[0],
                 x: 50, y: 50,
                 width: 60,
                 fromCenter: false
              });
         });

        </script>            
         <body>
            <img src="../image/0.jpg" class="drag-image" id="draggable"/>
        </div>
      </body>
    </html>