简体   繁体   English

canvas toDataURL没有返回完整的图像

[英]canvas toDataURL not returning a complete image

I'm building a jQuery plugin which watermarks images (and yes, i'm well aware of the multitudinal drawbacks of a javascript/html5 watermarking system but just ignore that for now.) The basic method for each image is: 我正在构建一个jQuery插件,用于水印图像(是的,我很清楚javascript / html5水印系统的众多缺点,但暂时忽略它。)每个图像的基本方法是:

  • paste the image to the background of a canvas 将图像粘贴到画布的背景上
  • add the data for a watermark image over that, 添加水印图像的数据,
  • replace the src of the original image with that of the canvas (which now contains the watermark.) 将原始图像的src替换为画布的src(现在包含水印。)

Now it appears to work fine if I replace the image element with the canvas itself.. all of the elements appear on the canvas. 现在,如果我用画布本身替换图像元素,它似乎工作正常..所有元素都出现在画布上。 But when I get the dataURL of the canvas, everything but the last image drawn onto it appears. 但是当我得到画布的dataURL时,除了最后一个图像之外的所有图像都显示出来。 I wouldn't even mind except this plugin also needs to replace the links to images as well, and so replace the hrefs with data urls (with the watermark.) 我甚至不介意,除了这个插件也需要替换图像的链接,所以用数据网址(带水印)替换hrefs。

This is the current code: 这是当前的代码:

(function($){

    $.fn.extend({

        cmark: function(options) {

            var defaults = {
                type: 'image',
                content: 'watermark.png',
                filter: 'darker',
                scale:300,
                box: {
                    top         :   0.5,
                    left        :   0.5,
                    width       :   0.75,
                    height      :   0.75,
                    bgcolor     :   '#000000',
                    bgopacity   :   0.5,
                    fgopacity   :   1
                },

                callback_unsupported: function(obj){
                    return obj;
                }

            }

            var getScale = function(w, h, scale){
                ratio = Math.min(scale/w, scale/h);
                scalew = Math.round(ratio*w);
                scaleh = Math.round(ratio*h);
                return [scalew,scaleh];
            }



            var options =  $.extend(defaults, options);

            return this.each(function() {

                obj = $(this);

                canvas = document.createElement('canvas');

                if(!window.HTMLCanvasElement){
                    return options.callback_unsupported(obj);
                }


                /*  if selecting for images, reset the images. Otherwise, 
                    we're replacing link hrefs with data urls. */

                if(obj.attr('src')){
                    target_img = obj.attr('src');
                }

                else if (obj.attr('href')){
                    target_img = obj.attr('href');
                }

                // get the filetype, make sure it's an image. If it is, get a mimetype. If not, return.

                ftype = target_img.substring(target_img.lastIndexOf(".")+1).toLowerCase();

                canvasbg = new Image();

                canvasbg.onload = function(){
                    iw = canvasbg.width;
                    ih = canvasbg.height;

                    scale = getScale(iw, ih, options.scale);

                    iw = scale[0];
                    ih = scale[1];

                    canvas.setAttribute('width', iw);
                    canvas.setAttribute('height', ih);

                    ctx = canvas.getContext('2d');

                    /* define the box as a set of dimensions relative to the size of the image (percentages) */

                    bw = Math.round(iw * options.box.width);
                    bh = Math.round(ih * options.box.height);

                    // for now the box will only ever be centered.
                    bx = Math.round((iw * options.box.top) - (bw/2));
                    by = Math.round(ih * options.box.left - (bh/2));

                    /* draw the box unless the opacity is 0 */
                    if(options.box.bgopacity > 0){
                        ctx.fillStyle = options.box.bgcolor;
                        ctx.globalAlpha = options.box.bgopacity;
                        ctx.fillRect(bx, by, bw, bh);
                    }

                    wm = new Image();

                    wm.onload = function(){
                        ww = wm.width;
                        wh = wm.height;

                        scalar = Math.max(bw, bh); // scale to within the box dimensions
                        scale = getScale(ww, wh, scalar);
                        ww = scale[0];
                        wh = scale[1];

                        ctx.globalCompositeOperation = options.filter;
                        ctx.drawImage(wm, bx, by, ww, wh);
                    }

                    wm.src = options.content;

                    ctx.drawImage(canvasbg, 0, 0, iw, ih);

                    obj.replaceWith(canvas);

                    $('body').append('<img src="'+canvas.toDataURL()+'">');

                    //obj.attr('src', canvas.toDataURL());
                }

                canvasbg.src = target_img;



            });
        }
    })
})(jQuery);

I added a line which dumps an image with the data url directly onto the page for testing and this is what I see... on the left is the canvas element, on the right is the image with the data url: 我添加了一行,将带有数据url的图像直接转储到页面上进行测试,这就是我看到的...左边是canvas元素,右边是带有数据url的图像:

左边是画布,右边是图像

So yeah, this has had me stumped for a couple of days now. 所以,是的,这让我难倒了好几天了。 I'm probably missing something horribly obvious but I can't see it. 我可能错过了一些非常明显的东西,但我看不到它。

... edited because the example is no longer online. ...编辑,因为示例不再在线。 sorry. 抱歉。

First of all, don't build a string buffer that big for a tag. 首先,不要为标记构建一个大的字符串缓冲区。

var img = new Image();
img.src = canvas.toDataURL();
$('body').append(img);

Or if you prefer: 或者如果您愿意:

$('body').append($('<img>').attr('src', canvas.toDataURL()))

Second, you are getting there dataURL of the canvas before you draw the watermark. 其次,在绘制水印之前,您将获得画布的dataURL。 The drawing happens in the wm.onload callback function, which happens when the watermark loads. 绘图发生在wm.onload回调函数中,该函数在加载水印时发生。 That may not fire until way after canvasbg.onload fires off, which is where you get the dataURL. canvasbg.onload触发之后,这可能不会触发,这是您获取dataURL的地方。

So move the image append into code at the end of the wm.onload callback and you should be good. 因此,在wm.onload回调结束时将图像附加到代码中,你应该很好。

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

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