Javascript Canvas从图像获取数据并显示它

时间:2019-06-08 16:59:25

标签: javascript canvas imagedata

我不知道为什么这行不通。图像的src属性随新数据一起更改,但是该图像实际上不可见。我尝试了几种不同的图像。这只是浏览器中的javascript,并且需要Jquery。

<body>
<img src="" id="test">
</body>
<script>
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    let img = new Image();
    img.onload = getIt
    img.src = 'download.png';

    function getIt() {      
        canvas.width = this.width;
        canvas.height = this.height;
        const imageData = ctx.getImageData(0, 0, this.width, this.height);
        ctx.drawImage(this, canvas.width , canvas.height);
        ctx.putImageData(imageData, canvas.width, canvas.height);

        $('#test').get(0).src = canvas.toDataURL("image/png");
    }

</script>

我尝试了几种不同的图像,都是png。目前,这是该项目的全部代码,因此我预见不到任何可能干扰该项目的代码。

结果是这样,但是看不到图像:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAeCAYAAAAhDE4sAAAAMklEQVRIS+3SsQ0A....etc" id="test">

编辑:看来它可能是不正确地从图像中获取数据,但我不知道为什么...我的意思是为什么它会获取数据但不完整或不正确?

1 个答案:

答案 0 :(得分:1)

请尝试以下操作: (您不需要获取或放置图像数据)

您也正在这样做:ctx.putImageData(imageData, canvas.width, canvas.height);。这意味着您要在画布外部完全绘制图像。相反,请执行以下操作:ctx.putImageData(imageData, 0,0);

const canvas = document.createElement("canvas");

    const ctx = canvas.getContext("2d");
    let img = new Image();
    img.onload = getIt
    img.src = "download.png";

    function getIt() {    
        canvas.width = this.width;
        canvas.height = this.height;
        //draw the image onto the canvas
        ctx.drawImage(this, 0,0);
        //use the data uri 
        test.src = canvas.toDataURL("image/png");
    }
<img src="" id="test">
相关问题