简体   繁体   English

在html5画布中显示图像?

[英]to display an image in a html5 canvas?

I have an image location stored in a json file as a string.Now , i have to get the image location from the json file and have to display it in a html5 canvas.Please help me in doing this.I don't know how to retrieve the image path from the json file using javascript.this is the content of my json file. 我有一个图像位置作为字符串存储在json文件中。现在,我必须从json文件中获取图像位置并将其显示在html5画布中。请帮助我这样做。我不知道如何使用javascript从json文件中检索图像路径。这是我的json文件的内容。

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

I have to display this image in a html page. 我必须在html页面中显示此图像。 this is my java code to create the json file 这是我创建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();
            }
        }
    }

You need to store your JSON file with .jsonp extension. 您需要存储扩展名为.jsonp的JSON文件。 In that file do write your object like this: 在该文件中,这样编写对象:

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

Then you can request that file in <head> like this: 然后,您可以像这样在<head>请求该文件:

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

You can access the JSON contents as: 您可以通过以下方式访问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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM