繁体   English   中英

在html5画布中显示图像?

[英]to display an image in a 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();
            }
        }
    }

您需要存储扩展名为.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>

暂无
暂无

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

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