canvas的drawImage出现的问题 1C

如下是我的全部代码,在谷歌浏览器中运行,但是canvas就是画不出图片。求大神指点,哪里写的有问题?

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <div id="root">

    </div>
    <img id="preview" src="http://img02.tooopen.com/images/20140504/sy_60294738471.jpg" />
    <script>
        var img = document.getElementById('preview');

        document.getElementById('root').appendChild(convertImageToCanvas(img));
        function convertImageToCanvas(image) {
            var canvas = document.createElement("canvas");
            canvas.setAttribute('style','border:1px solid #000');
            canvas.getContext("2d").drawImage(image, 0, 0);
            canvas.width = image.width;
            canvas.height = image.height;

            return canvas;
        }
    </script>
</body>

</html>

2个回答

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
    <div id="root">

    </div>
    <img id="preview" src="http://img02.tooopen.com/images/20140504/sy_60294738471.jpg" />
    <script>
        var img = document.getElementById('preview');

        document.getElementById('root').appendChild(convertImageToCanvas(img));
        function convertImageToCanvas(image) {
            var canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            canvas.setAttribute('style','border:1px solid #000');
            canvas.getContext("2d").drawImage(image, 0, 0);


            return canvas;
        }
    </script>
</body>

</html>

交换一下顺序就可以了

showbo
支付宝加好友偷能量挖 对的,重新设置canvas的width/height会重绘导致原来的图像丢失
大约 3 年之前 回复

图片说明
运行的结果是这样的。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐