我是Javascript的新手,我想修改输入表单中给出的任何远程图像的亮度 我试过使用Canvas,但我得到了这个issue。 我想通过" file:///test.html"直接使用以下代码。我怎样才能做到这一点?
<html>
<head>
<script type="text/javascript">
function readImg() {
img = new Image();
url = document.getElementById('url').value;
document.getElementById('showImg').innerHTML='<img src="'+ url +'" />';
img.src = url;
canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
img.crossOrigin = "Anonymous";
imgData = ctx.getImageData(0,0,canvas.width,canvas.height); // not working !!
brightness(imgData);
}
function brightness(imgData) {
var dataimg = imgData.data;
for (var i = 0; i < dataimg.size; i += 4 ) {
dataimg[i] += 10;
dataimg[i+1] += 10;
dataimg[i+2] += 10;
}
}
</script>
</head>
<body>
<input id="url" type="text" onChange="readImg()"></input>
<div id='showImg'></div>
</body>
</html>
答案 0 :(得分:0)
您必须让Chrome显式访问本地html文件中的本地文件。 您必须使用 - allow-file-access-from-files 标志运行Chrome。
"C:\PathTo\Chrome.exe" --allow-file-access-from-files
您可以在此处找到有关它的更多信息,因为它已经讨论过了: https://stackoverflow.com/a/18587027/4103991
@EDIT:// 在img.onload事件处理程序中执行与img元素相关的命令。 你的代码看起来应该是这样的:
<html>
<head>
<script type="text/javascript">
function readImg() {
img = new Image();
url = document.getElementById('url').value;
document.getElementById('showImg').innerHTML='<img src="'+ url +'" />';
canvas = document.createElement("canvas");
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
imgData = ctx.getImageData(0,0,canvas.width,canvas.height);
brightness(imgData);
}
img.src = url;
img.crossOrigin = "Anonymous";
}
function brightness(imgData) {
var dataimg = imgData.data;
for (var i = 0; i < dataimg.size; i += 4 ) {
dataimg[i] += 10;
dataimg[i+1] += 10;
dataimg[i+2] += 10;
}
}
</script>
</head>
<body>
<input id="url" type="text" onChange="readImg()"></input>
<div id='showImg'></div>
</body>
</html>