Javascript: Image Object & # 8594; HTML image element
The code preloads the image into an image object and then (presumably) sets it to the src image element to HTML:
<!DOCTYPE html>
<html>
<head>
<script language="javascript">
window.onload = function () {
var oImage = new Image();
oImage.onload = function () {
document.getElementById('myImage').src = oImage;
alert('done');
};
oImage.src = 'image1.jpg';
}
</script>
</head>
<body>
<img id="myImage" src="" />
</body>
</html>
Why doesn't it work?
+1
source to share
1 answer
Try
<!DOCTYPE html>
<html>
<head>
<script language="javascript">
window.onload = function () {
var oImage = new Image();
oImage.onload = function () {
document.getElementById('myImage').src = oImage.src;
alert('done');
};
oImage.src = 'image1.jpg';
};
</script>
</head>
<body>
<img id="myImage" src="" />
</body>
</html>
You cannot set the src image, you must set it to the src image . (PS: added semicolon at the end and changed .src = oImage
to .src = oImage.src
)
+6
source to share