简体   繁体   English

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

[英]Javascript Canvas get data from image and display it

I've no idea why this doesn't work. 我不知道为什么这行不通。 The src attribute of the image is changed with the new data, but the image is not actually visible. 图像的src属性随新数据一起更改,但是该图像实际上不可见。 I tried with several different images. 我尝试了几种不同的图像。 It's just javascript in a browser and Jquery is required. 它只是浏览器中的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>

I tried with several different images, all png. 我尝试了几种不同的图像,都是png。 At the moment this is the entire code for the project so I don't foresee anything that could be interfering with it. 目前,这是该项目的全部代码,因此我预见不到任何可能干扰该项目的代码。

The result is this but the image cannot be seen: 结果是这样,但是看不到图像:

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

EDIT: It seems like it might be getting the data from the image incorrectly but I've no idea why...I mean why would it get the data but be incomplete or incorrect? 编辑:似乎它可能是不正确地从图像中获取数据,但我不知道为什么...我的意思是为什么它会获取数据但不完整或不正确?

Please try this: (You don't need to get or put the image data) 请尝试以下操作:(您无需获取或放置图像数据)

Also you were doing this: ctx.putImageData(imageData, canvas.width, canvas.height); 您也正在这样做: ctx.putImageData(imageData, canvas.width, canvas.height); . This means that you are drawing the image totally outside the canvas. 这意味着您要在画布外部完全绘制图像。 Do this instead: ctx.putImageData(imageData, 0,0); 改为执行此操作: 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">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM