+ Start a Discussion
Ron McCrereyRon McCrerey 

Static Resource Zipped Image File won't Load from Javascript

I have a Zipped Static Resource which includes a .js file and several images.  The images load fine from the HTML with following :
<img src = "{!URLFOR($Resource.images,'img/')}ToolBumper24S7DS120x140.png"/>

but the following code in Javascript produces an undefined error.

image.onload = image.addEventListener("load", function(){                                 
          canvas.drawImage(image, x, y, w, h);
          }, false);
          
image.onload =  image.addEventListener("error", function(e){
          console.log("error loading image " + is + "  " + JSON.stringify(e) );
});

image.src = "{!URLFOR($Resource.images,'img/')}ToolBumper24S7DS120x140.png";

Why does the image not load?

 
Best Answer chosen by Ron McCrerey
Terence_ChiuTerence_Chiu
The following worked for me, perhaps it will help you resolve your issue. I uploaded a resource zip file with a folder named "img". Within the img folder is a png file.

<apex:page >
    <!--<apex:image url="{!URLFOR($Resource.ImageTest,'img/Capture.PNG')}" />-->
   
    <img id="imageid"/>
   
    <script>
        var url = "{!URLFOR($Resource.ImageTest,'img/Capture.PNG')}";
	console.log(url);​
        var image = document.getElementById('imageid');
        image.src = url;
    </script>
</apex:page>


 

All Answers

Terence_ChiuTerence_Chiu
The syntax looks a bit off. Can you try the following.

<img src = "{!URLFOR($Resource.images,'img/ToolBumper24S7DS120x140.png')}"/>
 
Ron McCrereyRon McCrerey
Your suggestion works in the HTML.  But I am trying to get it to work in javascript. In the script file it will generate the following error:
Expected an identifier and instead saw '<'

I believe the problem is that "{!URLFOR($Resource.images,'img/')}"  this is not being resolved but is being processed as as a string literal.
In other words it is being processed as  "!URLFOR($Resource.images,'img/')}ToolBumper24S7DS120x140.pngToolBumper24S7DS120x140.png')}"
and it should be resolved and processed as something like this ''/resource/1438357662000/images/img/ToolBumper24S7DS120x140.png''
Terence_ChiuTerence_Chiu
The following worked for me, perhaps it will help you resolve your issue. I uploaded a resource zip file with a folder named "img". Within the img folder is a png file.

<apex:page >
    <!--<apex:image url="{!URLFOR($Resource.ImageTest,'img/Capture.PNG')}" />-->
   
    <img id="imageid"/>
   
    <script>
        var url = "{!URLFOR($Resource.ImageTest,'img/Capture.PNG')}";
	console.log(url);​
        var image = document.getElementById('imageid');
        image.src = url;
    </script>
</apex:page>


 
This was selected as the best answer