如何将html5画布图像转换为json对象?

时间:2014-01-11 05:00:27

标签: javascript html5 canvas html5-canvas

嗨,我必须将一组图像转换为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>

1 个答案:

答案 0 :(得分:3)

<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);

演示:http://jsfiddle.net/LcnbX/

ctx.getImageData()将返回一个对象 JSON.stringify(data)将为您生成json字符串(请参阅控制台)