嗨,我必须将一组图像转换为json对象.但是,第一步我试图对单个图像进行处理,但我不知道是否创建了json对象.请帮助我检查一下是否创建对象.
这是代码:
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset=utf-8 />
<title>HTML5 Example: Canvas</title>
<script>
function drawOnCanvas() {
var ctx=document.getElementById("mycanvas").getContext('2d');
var image=new Image();
image.src="2000.png";
image.onload=function() {
ctx.drawImage(image,140,0);
}
imageData = ctx.getimageData(0, 0, mycanvas.width, mycanvas.height);
var jsontext=JSON.stringify(imageData.data);
}
window.addEventListener('load', drawOnCanvas, true);
</script>
</head>
<body>
<canvas width="1000" height="1000" id="mycanvas"></canvas>
</body>
</html>
解决方法:
<canvas id="canvas" width="400" height="400">
</canvas>
<canvas id="c2" width="400" height="400"></canvas>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.rect(5, 5, 300, 250);
ctx.stroke();
ctx.arc(150, 150, 100, 0, Math.PI, false);
ctx.stroke();
canvas.addEventListener("click", function (){
var data = ctx.getimageData(0, 0, canvas.width, canvas.height);
console.log(data);
console.log(JSON.stringify(data));
var c2 = document.getElementById("c2");
var ctx2 = c2.getContext("2d");
ctx2.putimageData(data, 0, 0);
}, false);
ctx.getimageData()将返回一个对象
JSON.stringify(data)将为您生成json字符串(请参阅控制台)