JavaScript 如何获取图像数据URL
要获得画布的图像数据URL,我们可以使用画布对象的toDataURL()方法,该方法将画布绘制转换为64位编码的PNG URL。如果你想要图像数据URL是jpeg格式,可以将image/jpeg作为toDataURL()方法的第一个参数传递。
你可以通过将0到1之间的数字作为toDataURL()方法的第二个参数来控制jpeg图像的质量。根据toDataURL()方法的要求,任何绘制到画布上的图像必须在与执行代码相同域的Web服务器上托管。如果不满足此条件,将抛出SECURITY_ERR异常。
示例1
以下示例演示了在JavaScript中获取图像URL的过程 –
<!DOCTYPE html>
<html>
<head>
<title>Get URL of Image</title>
</head>
<body>
<input type='f' onchange="readURL(this);" />
<br />
<br />
<button id="tCD" onclick="togCan()">Hide canvas</button> <button id="tDU" onclick="togDU()">DataURL hide</button>
<br/>
<br/>
<textarea id="dU" rows="4" cols="100">
</textarea>
<br/>
<canvas id="myCan"></canvas>
<script>
function rdURL(ip) {
if (ip.files && ip.files[0]) {
var reader = new FileReader();
reader.addEventListener(
"load",
function() {
var avatarImg = new Image();
var src = reader.result;
avatarImg.src = src;
document.getElementById("dU").innerText = src;
avatarImg.onload = function() {
var c = document.getElementById("myCan");
var ctx = c.getContext("2d");
ctx.canvas.width = avatarImg.width;
ctx.canvas.height = avatarImg.height;
ctx.drawImage(avatarImg, 0, 0);
};
},
false
);
reader.readAsDataURL(ip.files[0]);
}
}
function togCan() {
var canvas = document.getElementById("myCan");
if(canvas.style.display == "none"){
canvas.style.display = "block";
document.getElementById("tCD").innerText = "Canvas hide";
}
else {
canvas.style.display = "none";
document.getElementById("tCD").innerText = "Canvas show";
}
}
function toggleDataUrl() {
var area = document.getElementById("dU");
if(area.style.display == "none"){
area.style.display = "block";
document.getElementById("tDU").innerText = "Data url hide";
}
else {
area.style.display = "none";
document.getElementById("tDU").innerText = "Data url show";
}
}
</script>
</body>
</html>
示例2
以下是使用JavaScript读取文件的另一个示例 −
var fs = require("fs");
console.log("Going to write into existing file");
// Open a new file with name input.txt and write Simply Easy Learning! to it.
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
// Read the newly written file and print all of its content on the console
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});