Javascript 我可以从画布元素获取图像并在 img src 标签中使用它吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10257781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:31:23  来源:igfitidea点击:

Can I get image from canvas element and use it in img src tag?

javascripthtmlimagecanvas

提问by kassprek

Is there possibility to convert the image present in a canvas element into an image representing by img src?

是否有可能将画布元素中存在的图像转换为由 表示的图像img src

I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader()or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.

我需要在一些转换后裁剪图像并保存它。我在互联网上找到了一个视图函数,例如:FileReader()or ToBlop(), toDataURL(), getImageData(),但我不知道如何在 JavaScript 中正确实现和使用它们。

This is my html:

这是我的 html:

<img src="http://picture.jpg" id="picture" style="display:none"/>
<tr>
    <td>
        <canvas id="transform_image"></canvas>
    </td>
</tr>
<tr>
    <td>
        <div id="image_for_crop">image from canvas</div>
    </td>
</tr>

In JavaScript it should look something like this:

在 JavaScript 中,它应该是这样的:

$(document).ready(function() {
    img = document.getElementById('picture');
    canvas = document.getElementById('transform_image');

    if(!canvas || !canvas.getContext){
        canvas.parentNode.removeChild(canvas);
    } else {
        img.style.position = 'absolute';
    }
    transformImg(90);
    ShowImg(imgFile);
}

function transformImg(degree) {
    if (document.getElementById('transform_image')) {
        var Context = canvas.getContext('2d');
        var cx = 0, cy = 0;
        var picture = $('#picture');
        var displayedImg = {
            width: picture.width(),
            height: picture.height()
        };   
        var cw = displayedImg.width, ch = displayedImg.height
        Context.rotate(degree * Math.PI / 180);
        Context.drawImage(img, cx, cy, cw, ch);
    }
}

function showImg(imgFile) {
    if (!imgFile.type.match(/image.*/))
    return;

    var img = document.createElement("img"); // creat img object
    img.id = "pic"; //I need set some id
    img.src = imgFile; // my picture representing by src
    document.getElementById('image_for_crop').appendChild(img); //my image for crop
}

How can I change the canvas element into an img srcimage in this script? (There may be some bugs in this script.)

如何img src在此脚本中将画布元素更改为图像?(此脚本中可能存在一些错误。)

回答by Zeta

canvas.toDataURL()will provide you a data urlwhich can be used as source:

canvas.toDataURL()将为您提供一个可用作来源的数据网址

var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);

See also:

也可以看看:

回答by honkskillet

Do this. Add this to the bottom of your doc just before you close the body tag.

做这个。在关闭 body 标签之前,将其添加到文档底部。

<script>
    function canvasToImg() {
      var canvas = document.getElementById("yourCanvasID");
      var ctx=canvas.getContext("2d");
      //draw a red box
      ctx.fillStyle="#FF0000";
      ctx.fillRect(10,10,30,30);

      var url = canvas.toDataURL();

      var newImg = document.createElement("img"); // create img tag
      newImg.src = url;
      document.body.appendChild(newImg); // add to end of your document
    }

    canvasToImg(); //execute the function
</script>

Of course somewhere in your doc you need the canvas tag that it will grab.

当然,在您的文档中的某个地方,您需要它会抓取的画布标签。

<canvas id="yourCanvasID" />

回答by limoragni

I′ve found two problems with your Fiddle, one of the problems is first in Zeta′s answer.

我发现你的 Fiddle 有两个问题,其中一个问题是 Zeta 的回答中的第一个。

the method is not toDataUrl();is toDataURL();and you forgot to store the canvas in your variable.

该方法不toDataUrl();toDataURL();你忘了画布存储在您的变量。

So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/

所以小提琴现在工作正常http://jsfiddle.net/gfyWK/12/

I hope this helps!

我希望这有帮助!

回答by skyrail

canvas.toDataURLis not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images. Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.

canvas.toDataURL如果原始图像 URL(相对或绝对)与网页不属于同一域,则不起作用。通过书签和包含图像的网页中的简单 javascript 进行测试。看看 David Walsh 的工作示例。将html和图片放在自己的web服务器上,将原始图片切换为相对或绝对网址,更改为外部图片网址。只有前两种情况有效。

回答by Si Simon

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

更正了小提琴 - 更新显示复制到画布中的图像......

And right click can be saved as a .PNG

右键单击可以另存为 .PNG

http://jsfiddle.net/gfyWK/67/

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

加上小提琴页面上的JS......

Cheers Si

干杯斯

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

目前正在考虑将其保存到服务器上的文件 --- ASP.net C#(.aspx 网页表单)任何建议都会很酷....