在第一个页面上有一个按钮,单击后会打开第二个页面,允许您在画布上绘制图片。绘制完上述图片后,可以单击"发布"按钮,将画布转换为图像URL并关闭第二个页面窗口。
然后我希望图像自动显示在原始的第一页上。
问题是,我似乎无法将新的图像URL输出传递回第一个页面。两个脚本都封装在window.onload中,这似乎不允许我全局访问变量或函数。我尝试过将pubNow函数放在window.onload之外,该函数将画布转换为图像,但它将代码放在了作用域之外,并且有几个变量返回了未定义的值。如何传递此变量?
这是下面的代码。请只使用香草Javascript。
注意:每个页面都有自己的HTML、CSS和JS文件。我想把一个函数的输出从一个JS文件传递到另一个。
//HTML
<script src= 'file1.js'></script>
<script src= 'file2.js'></script>
//JS File1
window.onload = function(){
//code that needs to use output of pubNow() after publish button is clicked on second page
}
//JS File2
const canvas = document.getElementsByClassName('draw');
const draw = canvas[0].getContext('2d');
//code that allows user to draw
const publish = document.getElementsByClassName('publish');
publish[0].addEventListener('mousedown', pubNow);
publish[0].addEventListener('mousedown', close);
window.onload = function () {
function pubNow (canvas){
const image = new image();
image.src = canvas.toDataURL('image/png');
return image;
}
function close (){
window.close();
}
}
您可以使用postMessage
:
index.html
<button id="open-btn">Open the canvas page</button>
<img id="img" src="" alt="" />
<script>
document.getElementById("open-btn").addEventListener("click", openCanvasPage);
window.addEventListener("message", function(msg) {
document.getElementById("img").setAttribute("src", msg.data);
});
function openCanvasPage() {
open("draw.html");
}
</script>
canvas.html
<canvas id="canvas" width="500" height="500"></canvas>
<button id="publish-btn">Publish</button>
<script>
document.getElementById("publish-btn").addEventListener("click", publishDrawing);
function publishDrawing() {
// `opener` is the window that spawned this one
opener.postMessage(canvas.toDataURL(), "*");
close();
}
</script>
演示