在html5画布中显示图像?

时间:2014-02-28 05:41:33

标签: javascript json html5 canvas html5-canvas

我有一个图像位置存储在json文件中作为字符串。现在,我必须从json文件中获取图像位置,并且必须在html5画布中显示它。请帮我做这个。我不要知道如何使用javascript从json文件中检索图像路径。这是我的json文件的内容。

{"image1":"\/root\/Desktop\/project\/Screenshot.png"}

我必须在html页面中显示此图像。 这是我创建json文件的java代码

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import java.io.FileWriter;
import java.io.FileReader;
import javax.xml.bind.DatatypeConverter;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

    public class Simple27 
    {
        public static void main(String[] args) throws IOException
        {

            BufferedImage img=ImageIO.read(new File("/root/Desktop/project","Screenshot.png"));
            //the string is written into a json file
            try
            {
                FileWriter wr=new FileWriter("/root/Desktop/project/code/json/imagepath.jsonp");    
                String ip="/root/Desktop/project/Screenshot.png";
                JSONObject imgpath=new JSONObject();
                imgpath.put("image1",ip);
                wr.write(imgpath.toString());
                wr.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您需要存储扩展名为.jsonp的JSON文件。 在该文件中,请写下您的对象:

jsonContents = [ {"image1":"\/root\/Desktop\/project\/Screenshot.png"} ];

然后您可以像<head>这样请求该文件:

<script src="file://path to your jsonp file"></script> 

您可以访问JSON内容:

<script>
    console.log((jsonContents));
    var contents = jsonContents;

    for(var i=0;i<jsonContents.length;i++){

       var obj = jsonContents[i];
       var imageSrc = obj.image1;
       console.log(imageSrc);
       var img = new Image();
       img.src = imageSrc;
       context.drawImage(img,x,y);  //context = your context variable

    }

</script>