4

How do you pass an image as argument in a function/class or is this impossible and if it is how would I fix it? For example:

var tree = new Image();
tree.src = "img/statobj/tree.png"
function additem(dimage){
document.getElementById("myitems").rows[0].insertCell(0).innerHTML ='<div id="invetoryitem" >'+ this.dimage + '</div>'
console.log(dimage) //gets undefined
}

I've tried dimage.src and other methods but nothing I use seems to work :/

2
  • IIRC function(dimage) is invalid syntax Commented Mar 2, 2019 at 4:10
  • sorry, that was just an example, that's not my actual problem I'll just fix it Commented Mar 2, 2019 at 4:11

2 Answers 2

2

Pass it like you would any other, but to display it, use appendChild not innerHTML:

var tree = new Image();
tree.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
function showTree(dimage) {
  document.getElementById("div").appendChild(dimage);
  console.log(dimage);
}

showTree(tree);
<div id="div"></div>

If you do want to use innerHTML, make an <img> with the src being dimage.src:

var tree = new Image();
tree.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/eb/Ash_Tree_-_geograph.org.uk_-_590710.jpg/220px-Ash_Tree_-_geograph.org.uk_-_590710.jpg";
function showTree(dimage) {
  document.getElementById("div").innerHTML = "<img src='" + dimage.src + "'>";
  console.log(dimage);
}

showTree(tree);
<div id="div"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

You have to name the function and call it by passing the image as an argument. If you are using innerHTML you have to create the image tag and add the source of the image received to the function as argument

var tree = new Image();
tree.src = "img/statobj/tree.png"
function a(dimage){
document.getElementById("myitems").innerHTML ='<div id="invetoryitem" ><img src="'+dimage.src+ '"></div>'
console.log(dimage) //gets undefined
}
a(tree);
<body id="myitems"></body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.