1
我寫了一個不錯的插件,轉換IMG以帆布將img轉換爲canvas(帶有jquery插件),如何繼續使用canvas?
jQuery.fn.img2canvas = function() {
return this.each(function(){
if($(this).get(0).tagName=='IMG'&&$(this).parent().get(0).tagName!='CANVAS')
{
//alert($(this).get(0).tagName);
$(this).load(function()
{
var c = $("<canvas class=' img2canvas'>"+$(this).outerHTML()+"</canvas>");
//var c = $("<canvas></canvas>");
$(c).attr('width', this.width);
$(c).attr('height', this.height);
var ctx = $(c)[0].getContext("2d");
var img = new Image();
img.src = $(this).attr('src');
ctx.drawImage(img, 0, 0);
$(c).data('imgsrc', this.src);
$(c).attr('id', $(this).attr('id')+'_canvas');
$(this).replaceWith($(c));
});
}
});
};
到目前爲止好。但我無法繼續使用這些畫布。
$('img').img2canvas(); //creating the canvas
$('.img2canvas').css('border', '6px solid red'); //but there is no canvas yet
$('canvas').each(function(){alert($(this).data('imgsrc'));}); // still no canvas
$('.img2canvas').each(function(){alert($(this).data('imgsrc'));}); //still no canvas
沒有幫助。
我需要做些什麼來保持插件架構和能夠繼續在畫布元素上工作?你可以在這裏看到一個現場演示http://www.andcontext.com/inimad/sto_demo.php
thx爲您的輸入。
嗨,基本上這個插件中的「this」仍然包含IMG,「callback(this)」在圖片上起作用。 「回調($(c))」工作正常。謝謝。這是一種方法。這是正確的做法嗎? – 2010-09-06 12:46:23
是的,匿名回調是在事件觸發過程中發出回調的正常方式。 – RobertPitt 2010-09-06 15:03:12
嗨,我發佈了一個img2canvas函數清理代碼在這裏http://www.andcontext.com/comics/image-2-canvas-jquery-plugin - 我改變它的方式,它返回一個jQuery收集的新創建的畫布元素,並且畫布元素在成功插入DOM後觸發加載事件。這對於使用多個創建的畫布元素輕鬆進行工作是非常必要的。 – 2010-09-08 11:19:25