我不知道我遇到的这个 IE9 问题是否有解决方法,但这就是我想要做的。我的页面上的画布中有一张图片。我想将此画布图像复制到另一个画布,但在我创建的弹出窗口中。我在这个实验中遇到的是我可以将画布图像复制到同一页面上另一个动态创建的画布中,没问题。但是当我尝试在弹出窗口中执行此操作时,IE 给了我一个DOM Exception: TYPE_MISMATCH_ERR (17)。可悲的是,这似乎是 IE 的事情,因为我在 Chrome 中运行了相同的代码,并且它有效......所以这是我的代码。不过,您需要提供自己的图像,我使用了一个简单的 640x480 jpeg 文件。您还需要打开控制台,因为我正在执行 console.error。
<!DOCTYPE html>
<html>
<head>
<title>Canvas Copy Test</title>
<style>
#mainSrc {
border:1px solid red;
}
#dest01 {
width:640px;
height:480px;
border:1px solid blue;
}
</style>
<script>
var destWin; // Destination Window
window.onload=function()
{
var testImg = new Image();
testImg.src = "me.jpg";
testImg.onload = function()
{
var mainCanvas = document.getElementById("mainSrc");
var mainCtx = mainCanvas.getContext("2d");
mainCtx.drawImage(testImg,0,0);
}
var copyBtn = document.getElementById("copyBtn");
var copyWinBtn = document.getElementById("copy2WinBtn");
copyBtn.addEventListener("click",copyImage,false);
copyWinBtn.addEventListener("click",copy2Win,false);
}
// Copy Canvas Image to Another on the same page.
function copyImage()
{
var mainCanvas = document.getElementById("mainSrc");
var destCanvas = document.createElement("canvas");
var destDiv = document.getElementById("dest01");
destCanvas.width = mainCanvas.width;
destCanvas.height = mainCanvas.height;
var dCtx = destCanvas.getContext("2d");
dCtx.drawImage(mainCanvas,0,0);
destDiv.appendChild(destCanvas);
}
// Copy Canvas to Popup Window
function copy2Win()
{
var mainCanvas = document.getElementById("mainSrc");
try {
destWin = window.open("","destWin");
var destWinDoc = destWin.document;
var destWinHTML = "<!DOCTYPE html><html><head><title>POPUP</title><body><div id='destWinDiv' style='width:640px; height:480px; border:1px solid red'></div></body></html>";
destWinDoc.write(destWinHTML);
var destCanvas = destWinDoc.createElement("canvas");
var destDiv = destWinDoc.getElementById("destWinDiv");
destCanvas.width = mainCanvas.width;
destCanvas.height = mainCanvas.height;
var dCtx = destCanvas.getContext("2d");
dCtx.drawImage(mainCanvas,0,0);
destDiv.appendChild(destCanvas);
}
catch (err)
{
console.error(err);
}
}
</script>
</head>
<body>
<canvas id="mainSrc" width="640" height="480"></canvas>
<p>
<input type="button" name="Copy" value="Copy" id="copyBtn" />
<input type="button" name="Copy2Win" value="Copy To New Window" id="copy2WinBtn" />
</p>
<div id="dest01"></div>
</body>
</html>