我想我明白了。我必须创建一个临时画布元素,然后使用该canvas.toDataURL()
方法。不过,我很想找到一个不使用临时画布的解决方案。
// ctx1 and ctx2 are the 2d context objects for canvas1 and canvas2
var image_data = ctx1.getImageData( 23, 43, 20, 20 );
var image = getImageObjectByImageData( image_data );
ctx2.drawImage( image, 20, 30 );
function getImageObjectByImageData( $image_data )
{
var temp_canvas = document.createElement( 'canvas' );
temp_canvas.height = $image_data.width;
temp_canvas.width = $image_data.height;
var temp_context = temp_canvas.getContext( '2d' );
temp_context.putImageData( $image_data, 0, 0 );
var img = new Image();
img.width = $image_data.width;
img.height = $image_data.height;
img.src = temp_canvas.toDataURL();
return img;
}