Ajax响应图像元素到Canvas上

时间:2016-03-07 16:11:42

标签: javascript jquery html ajax canvas

我的网站上有一个上传照片按钮,可以在数据库中上传jpeg和png格式文件。成功完成后,它会在网站上显示照片。

成功完成后,ajax成功调用 after_success 函数,该函数将响应数据作为参数。

功能如下所示:

export class Taxon {
  constructor (
    public id: number,
    public name: string,
    public taxons: Taxon[]
    )
}

响应数据如下所示:

function after_success(data){


}

无论这个回复出现什么图像,我都试图在画布上绘制它。

我的解决方案:

<img src="uploads/56dda66be0181.png">

但这似乎不起作用。我如何在这个画布元素上获得图像?

注意: 使用 Div 元素和jquery .html(),它确实会在 Div 元素中显示图片。

2 个答案:

答案 0 :(得分:1)

好的,如果我理解正确,从上传的响应中你会得到一个图片标记,你想要将相同的图像绘制到具有id输出的画布上。

分解 - 1.你给了你从img标签的src获取图像网址作为回应。 你必须把它画上输出

var after_success = function(data){

    $('.someHiddenDiv').append(data);//append the response data to some div which is invisible. This is just to get jQuery to access the element as dom.

       var img = new Image();//well initialize a new image
       //on load of the image draw it on to canvas
       img.onload = function(){
           var canvas = document.getElementById('output');
           var ctx = canvas.getContext('2d');
           ctx.drawImage(img,10,10);//same as what you have done
       };
       img.src = $('.someHiddenDiv').find('img').attr('src');//get source from the image tag

    }

这应该有效!

答案 1 :(得分:0)

function after_success(data){
    $('#hiddendiv').html(data);
    var img=new Image();

    img.src=$('#hiddendiv').find('img').attr('src');

    $('#hiddendiv').hide();

        var canv=document.getElementById("output");
        var ctx=canv.getContext("2d");
    img.onload= function () {
        ctx.drawImage(img,10,10);
    }

这就是我为达到同样目的所做的。谢谢@ anubhab。给我一个关于如何做到这一点的公平想法。只是稍微调整了他的代码。

相关问题