我创建了一个对象,其中存储了用户的姓名,年龄,电子邮件和他上传的图像。 我想在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个这样的对象要显示在页面上。 任何解决方案都会有帮感谢
答案 0 :(得分: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();
}());
答案 1 :(得分: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+')';
这里我将图像显示为身体的背景图像,您也可以使用其他选项。