我正在尝试制作一个谷歌地图所在的div元素的“屏幕截图”。我使用html2画布,当涉及到“常规地图”(在地图上用一个或几个标记显示某个位置)时,不会遇到任何问题。然而,问题出在行车路线地图上——将两个点与计算路线连接起来的地图。这张地图可能不仅仅是一堆图层/图像,还使用了谷歌方向服务和方向显示服务,这些服务负责计算和绘制路线。(当html2画布试图重建“图像”时,这可能无法在后台完成)。最后,我收到了SecurityError:未能在“HTMLCanvasElement”上执行“toDataURL”:可能无法导出受污染的画布。
StackOverflow上有几个问题,非常接近这个案例,但没有一个描述完全相同的场景,也没有提供解决方案。
我知道这个问题的安全背景和CORS原则。分析标题时,可以找到行Access-Control-Allow-Origin: *。另外,每张地图的渲染都没有任何问题,所以我在这里看不到这个具体问题的根源。
此外,据我所知,这不能用谷歌的静态地图来覆盖,因为无法将路线绘制到静态地图。
这是代码:
html2canvas(document.getElementById('map'), {
//"proxy": "/html2canvasproxy.php", //proxy is not used
"logging": true,
"useCORS": true,
"onrendered": function (canvas) {
var img = new Image();
img.onload = function () {
img.onload = null;
img.setAttribute('crossOrigin', 'anonymous'); document.getElementById("output").appendChild(img); };
img.src = canvas.toDataURL("image/png"); //error line
}
});
一些旧的语法和丑陋的代码,但这应该是最终有效的东西……
screenShot ( i ) {
html2canvas( document.getElementById( 'map' + i), {
"logging": true,
"useCORS": true
} ).then( function ( canvas ) {
var encodedString = canvas.toDataURL( "image/png" );
// sending encoded base64 image to the server
googleMaps.$http.post( '/api/screenshots', {
appraisalId: googleMaps.$data.appraisal_id,
encodedScreenshot: encodedString,
tag: 'googlemaps',
index: i,
} ).then( function ( response ) {
googleMaps.setButtonsCaptions();
console.log( response.data.success );
}, function ( response ) {
console.log( response );
console.log( 'Problem while sending screenshot to the server' )
}.bind( googleMaps ) );
} );
}