我的要求是返回数据网址。但是,当我运行应用程序时,会出现运行时错误:
JavaScript运行时错误:未指定的错误。
这是我使用过的代码。临时路径是图像位置的路径。
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = "@tempPath";
context.drawImage(img, 40, 40);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);'
答案 0 :(得分:2)
尝试以下代码,它对我有用:
<body>
<canvas id="myCanvas"></canvas>
<img id="profileImg" alt=""/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
drawImg();
});
function drawImg() {
try {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = $('#profileImg');
context.drawImage(img, 40, 40);
var dataURL = canvas.toDataURL("image/jpeg");
alert(dataURL);
} catch (e) {
if (e.name == "NS_ERROR_NOT_AVAILABLE") {
// This is a bug in Firefox. The easiest fix is to simply keep trying until the error goes away,
//since no event fires at the correct time.
// Wait before trying again; you can change the length of this delay.
setTimeout(drawImg, 100);
} else {
throw e;
}
}
}
</script>
</body>
也适用于IE。希望这会有所帮助。