我正在使用 HTML 5 画布创建一个纯 Javascript 图像大小调整器。我有一个将画布下载为图像文件的链接。
这适用于单个文件:
$( '#dl' ).on( 'click', function( e ) {
e.preventDefault();
downloadCanvas( this, 'test.png' );
} );
function downloadCanvas( link, filename ) {
link.href = $( '#preview canvas' )[0].toDataURL();
link.download = filename;
}
我一直在尝试一次单击获取多个文件,但不起作用,只下载了一张图片(最后一张画布):
function downloadCanvas( link, filename ) {
$( '#preview canvas' ).each( function(i) {
var dataUrl = this.toDataURL( 'image/png' )
console.log( dataUrl );
$( '#down' ).attr( {
href: this.toDataURL( 'image/png' ),
download: filename + i
} ).trigger( 'click' );
} );
}
这是相关的 HTML,Canvas 是由 JS 在文件拖放到 droparea 时动态添加的:
<div id="droparea">Drop image here</div>
<div class="clear"></div>
<div id="preview" class="clear">
<h1>Preview</h1>
</div>
<a id="dl" href="#">Download</a>
<a id="down" href="#">Hidden</a>
JS:
$( '#droparea' ).on( 'dragover dragenter', function( e ) { e.preventDefault(); e.stopPropagation(); } )
.on( 'drop', function( e ) {
e.preventDefault();
loadImage( e.originalEvent.dataTransfer.files[0] );
} );
function render( src ) {
var image = new Image();
image.onload = function() {
var canvas = $( '<canvas>' ),
ctx = canvas[0].getContext( "2d" );
ctx.clearRect( 0, 0, canvas.width, canvas.height );
image.width *= maxH / image.height;
image.height = maxH;
canvas[0].width = image.width;
canvas[0].height = image.height;
ctx.drawImage( image, 0, 0, image.width, image.height );
$( '#preview' ).append( canvas ).show();
};
image.src = src;
}
function loadImage( src ) {
if( !src.type.match( /image.*/ ) ) {
console.log( "The dropped file is not an image: ", src.type );
return;
}
var reader = new FileReader();
reader.onload = function( e ) {
render( e.target.result );
};
reader.readAsDataURL( src );
}
有什么建议么?