canvasrenderingcontext2d的drawImage()没有显示img

时间:2014-09-30 16:01:59

标签: javascript

我试图学习使用drawImage(),创建所有节点;图像为1000x500px但从不显示

<head>
</head>
<body>
    <script type = "text/javascript">
        var body, canvas, img, cxt;
        body = document.getElementsByTagName("body")[0];

        canvas = document.createElement("canvas");
        canvas.style.width = "1000px";
        canvas.style.height = "500px";
        body.appendChild(canvas);
        img = document.createElement("img");
        cxt = canvas.getContext("2d");
        img.onload = function () {
            cxt.drawImage(img,0,0,1000,500,0,0,1000,500);

        }

        img.src = "/clouds.png";
    </script>
</body>

2 个答案:

答案 0 :(得分:1)

您的代码在加载DOM之前运行,您尝试在元素创建之前将元素附加到正文。

你需要将代码包装在一个块中,该块将在DOM准备好后运行,或者更好,一旦整个窗口的内容完全加载:

Example

window.onload  = function () {
    var body, canvas, img, cxt;
    body = document.getElementsByTagName("body")[0];

    canvas = document.createElement("canvas");
    canvas.style.width = "400px";
    canvas.style.height = "400px";
    body.appendChild(canvas);
    img = document.createElement("img");
    cxt = canvas.getContext("2d");
    img.onload = function () {
        cxt.drawImage(img, 0, 0, 400, 400, 0, 0, 350, 200);
    }
    img.src = "http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=fde65a5a78c6";
};

答案 1 :(得分:1)

我使用的部分图像是白色的。所以它恰好发生了,这是我被裁剪的图像的一部分。