0

我制作了一个对象,其中存储了用户的姓名、年龄、电子邮件和他上传的图像。我想在 div 中显示他上传的图像(比如说),我不知道如何做这件事。我试过这个:

$(function () {
    $('img').load(function () {
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;
        // Copy the image contents to the canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
        localStorage[this.id] = canvas.toDataURL("image/png");
    })
})

但如何使用 javascript 或 jquery 显示此图像?(没有任何插件)我有 5 个这样的对象要显示在页面上。任何解决方案都会有所帮助。谢谢

4

2 回答 2

0

尝试这个

    var imgCanvas = document.createElement("canvas"),
    imgContext = imgCanvas.getContext("2d");

    // Make sure canvas is as big as the picture
    imgCanvas.width = this.width;
    imgCanvas.height = this.height;

    // Draw image into canvas element
    imgContext.drawImage(image, 0, 0, imgCanvas.width,imgCanvas.height);
    // Save image as a data URL
    imgInfom = imgCanvas.toDataURL("image/png");
    localStorage.setItem("imgInfo",imgInfom);


    document.body.style.background = 'url('+imgInfom+')';

在这里,我将图像显示为身体的背景图像,您也可以使用其他选项。

于 2014-10-24T18:33:41.423 回答
0

试试这个,效果很好

 <input type="file" id="image-input" />
        <img id="image-container" />
        <script type="text/javascript">
        (function(){
              /** @type {Node} */
          var imgInput = document.getElementById( "image-input" ),
              /** @type {Node} */
              imgContainer = document.getElementById( "image-container" ),
              /** Restore image src from local storage */
              updateUi = function() {
                imgContainer.src = window.localStorage.getItem( "image-base64" );
              },
              /** Register event listeners */
              bindUi = function(){
                imgInput.addEventListener( "change", function(){
                  if ( this.files.length ) {
                    var reader = new FileReader();
                    reader.onload = function( e ){
                      window.localStorage.setItem( "image-base64", e.target.result );
                      updateUi();
                    };
                    reader.readAsDataURL( this.files[ 0 ] );
                  }
                }, false );
              };

        updateUi();
        bindUi();
        }());
于 2014-07-10T08:10:32.080 回答