【发布时间】:2016-06-11 09:30:26
【问题描述】:
我是一名 JavaScript 初学者。 我想将画布导出为装饰的 png 图像(使用 fillText 绘制一些文本)。
但我不能因为以下错误。
Script from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Invalid response. Origin 'null' is therefore not allowed access.
如果你能给我一些建议,我很高兴。
以下是我的源码
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="myscript.js" crossorigin="anonymous"></script>
</head>
<body>
<h1>draw text to loaded image</h1>
<form>
<input type="button" value="draw on canvas" onclick="draw()">
</form>
<canvas id="mycanvas" width="400" height="400">
</canvas>
<!-- <form>
<input type="button" value="export to image" onclick="chgImg()">
</form> -->
<div><img id="newImg"></div>
</body>
<script src="myscript.js"></script>
</html>
myscript.js
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
function draw(){
var img = new Image();
//load local image
img.src = 'test.png';
img.onload = function () {
ctx.globalCompositeOperation = 'destination-over';
var pattern = ctx.createPattern(img, 'no-repeat');
ctx.fillStyle = pattern;
ctx.drawImage(img, 10, 10);
}
ctx.font = 'bold 20px Verdana';
ctx.textAlign = 'left';
ctx.fillStyle = 'red';
ctx.fillText('test', 20, 20, 200);
var dataURL = canvas.toDataURL();
document.getElementById("newImg").src = dataURL;
console.log(dataURL);
chgImg();
}
// export to png
function chgImg() {
var png = canvas.toDataURL();
document.getElementById("newImg").src = png;
}
【问题讨论】:
-
很可能您将页面加载为本地文件,这会在大多数浏览器中引起安全问题。您必须将其放在网络服务器上。
-
感谢@hindmost 的建议。我计划将它作为一个带有电子的桌面应用程序。所以,我不想使用服务器。你有什么好主意吗?
标签: javascript html canvas cors