I am using VSCODE to make a blackjack game using HTML, CSS and javascript. I have defined a button that on clicking gives an image(that is stored in computer). Every time I refresh the live server(chrome), it says NOT ALLOWED TO LOAD LOCAL RESOURCE and FAILED TO LOAD RESOURCE: 404 not found. I am new to web development and need help with this project.
let blackjackGame = {
'you': {'scoreSpan': '#your_blackjack_result', 'div':'#your_box', 'score':0 },
'dealer': {'scoreSpan': '#dealer_blackjack_result', 'div':'#dealer_box', 'score':0 }
};
const YOU = blackjackGame['you']
const DEALER = blackjackGame["dealer"]
function blackjackHit() {
var cardImage = document.createElement('img');
cardImage.src = 'D:\Software Course\JS-Basics\Blackjack\images\Q.png';
document.querySelector(YOU['div']).appendChild(cardImage);
}
document.querySelector("#blackjack_hit_button").addEventListener("click", blackjackHit);
Every time I refresh the live server(chrome)
The web application is running from a server, even if it's one installed locally or only temporarily hosted within Visual Studio. As a result, this path won't work:
cardImage.src = 'D:\Software Course\JS-Basics\Blackjack\images\Q.png';
Because this is a file system path, not a web server URL. The browser doesn't want to mix those for security reasons. Instead, provide a URL for the file. Which might be something like:
cardImage.src = '/images/Q.png';
Finding out the URL is really up to you. But it'll be some path relative to the URL of the page being viewed in the browser.
You must use the correct local path from your computer. Then change the backslashs () to forward slashes (/) and add "file:///" before the path, so:
cardImage.src = 'file:///D:/Software Course/JS-Basics/Blackjack/images/Q.png';
function display_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Add image
Related
I have a web page (classic asp) with a link to a local IP address, as follows:
Link
If the local IP address is unavailable the web browser eventually times out and displays its own error message.
What I want to do is: catch the timeout before the browser displays its default error page and display an error on the same web page, next to the "Link".
e.g. Well Pump<div id="timeoutmsg">offline</div>
I am guessing I need some JavaScript and the timeout function, but I don't know where to begin.
Found this awesome workaround using pure javascript, no JScript, no ajax, no external libraries.
Works at treat:
Just need to upload a "test.gif" file to the local site(s).
var url = 'http://192.168.1.89';
var img = new Image();
img.src = url + '/test.gif';
img.onload = function() {
document.getElementById("msg").innerHTML = "";
window.location.href = url;
}
img.onerror = function() {
document.getElementById("msg").innerHTML = "offline";
}
first a little bit of context.
I'm working on a React web app and my object, Product, it has an array of images. The image object is pretty simple: { url: string, id: string }. The images are loading fine as you can see bellow:
When you click on the scissors icon it pops up a crop container. The crop container uses react-cropper, internally what that package does is the following:
//...
if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {
if (!crossOrigin) {
crossOrigin = 'anonymous';
} // Bust cache when there is not a "crossOrigin" property (#519)
crossOriginUrl = addTimestamp(url);
}
this.crossOrigin = crossOrigin;
this.crossOriginUrl = crossOriginUrl;
var image = document.createElement('img');
if (crossOrigin) {
image.crossOrigin = crossOrigin;
}
image.src = crossOriginUrl || url;
image.alt = element.alt || 'The image to crop';
this.image = image;
//...
Sometimes the image loads normally but most of the time I get the error:
Access to image at 'https://url.to.image?timestamp=1639579791237' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
That timestamp param is added by react-cropper to avoid CORS error. I did a deploy to my DEV environment to see if it would work in a live scenario but still got the same error.
Does anyone know what could be happening?
I have json feed that gives me thumbimage url.
This returns url like /webapps/CC/fileAPI/edc_eventcal/Celebrations_Todmorden%20Mills%20Harvest%20Festival_th__Vb2eHh-nEpJ8xLLEU5UFw.png
Now, before /webapps/ It needs "app.toronto.ca" to get the full path. So I've replaced "localhost" into "app.toronto.ca" like so. And it gives me full path to image.
Now, the trouble is that, even though I retrieve full URL, image.src syntax will still force computer to add 'Localhost:5000/' to my perfectly assembled URL.
function displayEvent(array,i){
var image_url = array[i].calEvent.thumbImage.url;
var image =new Image();
var hostname = location.hostname;
toronto_host = hostname.replace("localhost","app.toronto.ca") +
image_url;
alert(toronto_host); //this give me pull URL path//
image.src = toronto_host;
alert(image.src);
// this gives localhost:5000/what_i_had_in_toronto_host//
document.getElementById("party_picture").appendChild(image);
};
since no image path starts with http://localhost:5000/... i can't use any image while i'm testing the site.
Any way i could assign image src with the correct url without localhost part?
thank you!
Image src attribute will always append the localhost ( or where the page originates from ), if you don't provide a complete URL ( in your case you provide everything except the protocol ).
toronto_host = hostname.replace("localhost","//app.toronto.ca") +
image_url;
// ^ appending '//' before your
// location will force the browser
// to set the protocol to the current
// one of the page.
This will make your img.src to behave as expected.
I have a ASP.NET website that gets published to a web server that has multiple sites. For example:
www.example.com/SiteA or www.example.com/SiteB
Plus I also test the site locally before publishing, for example at localhost:12345
When I specify a path for an image, for example: /Images/exampleImage.gif, this works when running the site locally, since the Images folder is in the root directory. localhost:12345/Images/exampleImage.gif is the correct path in this case.
But when published to the web server, for example to www.example.com/SiteA, the same path tries to go to www.example.com/Images/exampleImage.gif and the image doesn't appear correctly.
Also, this is only for HTML controls, as with a ASP control, I know I can just use the tilde (~/Images/exampleImage.gif) and it'll know to look at the site's root directory, which is www.example.com/SiteA/Images/exampleImage.gif.
For my case, It'd be strongly preferred to stay with an HTML control.
Edit: The reason for this is because I have JavaScript that changes the image of a html img control based on if a div is hidden:
function Toggle(commId, imageId) {
var div = document.getElementById(commId);
var img = document.getElementById(imageId);
if (div.style.display == 'none') {
div.style.display = 'inline';
img.src = "/Images/minus.gif";
} else {
div.style.display = 'none';
img.src = "/Images/plus.gif";
}
}
How could I get the path to the images folder, relative to the root of the site when there's folders for each site on a server, as well as still working on localhost?
You'll have to use code to do the ~/ or publish a new virtual directory called "/Images" on your server that contains the images.
I didn't know you could put embedded C# code in JavaScript, but figured it out by just doing :
function Toggle(commId, imageId) {
var div = document.getElementById(commId);
var img = document.getElementById(imageId);
if (div.style.display == 'none') {
div.style.display = 'inline';
img.src = "<%= ResolveUrl("~/Images/minus.gif") %>";
} else {
div.style.display = 'none';
img.src = "<%= ResolveUrl("~/Images/plus.gif") %>";
}
}
Since the ResolveUrl method can take the tilde (~) for the path value and knows the websites root directory over the server's.
You can also use the embedded code with the same ResolveUrl method directly in the src attribute of the img html control (and other attributes/controls), in case anyone runs into this same issue but with just the HTML controls.
I'm a newbie in HTML5+JS, I want to develop an hybrid app using ocrad.js.
The code given below, downloaded from github page is perfectly working for me(Chrome 32.0.1).
<html>
<head>
</head>
<body>
<script src="../ocrad.js"></script>
<script>
function OCRImage(image){
var canvas = document.createElement('canvas')
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
canvas.getContext('2d').drawImage(image, 0, 0)
return OCRAD(canvas)
}
function OCRPath(url, callback){
var image = new Image()
image.src = url;
image.onload = function(){ callback(OCRImage(image)) }
}
function OCRFile(file, callback){
var reader = new FileReader();
reader.onload = function(){ OCRPath(reader.result, callback); }
reader.readAsDataURL(file)
}
</script>
<input type="file" onchange="OCRFile(this.files[0], function(text){alert(text)})">
</body>
</html>
When I called OCRAD() API in my code its giving Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data.
My CODE
<html>
<head>
<script src="../ocrad.js"></script>
<body>
<canvas id="cancan" width="800", height="500">Test image</canvas>
<script type="text/javascript">
function imageLoaded(ev) {
element = document.getElementById("cancan");
c = element.getContext("2d");
im = ev.target;
width = element.width;
height = element.height;
c.drawImage(im, 0, 0);
var data1=OCRAD(c);
console.log(data1);
}
im = new Image();
im.src = "message.png";
im.onload = imageLoaded;
</script>
</body>
</html>
I have seen similar Stackoverflow Q&A here but it didn't help me to solve the issue. Please answer if any one had any comment on this issue who have worked with Ocrad.js.
OR
Is there anyother way to pass my image file (here message.png in second code example) as an argument to OCRFile() function in first code example ? (Simply I want to pass an image stored in an local file URL to OCRAD() Call to return text. )
Thanks in advance.... :)
It is a cross-origin issue which is a security mechanism in browsers.
You will either need to:
Move image to same origin as the page (origin = domain, port and protocol)
Request CORS usage from the other origin if you can't move the image
Use a proxy page to load the image (see one in action here - note: I do not know this site so use only for testing with non-critical data).
A request can be made like this (assuming im contains the image you want to OCR treat):
function imageLoaded(ev) {
element = document.getElementById("cancan");
c = element.getContext("2d");
width = element.width;
height = element.height;
c.drawImage(this, 0, 0); // 'this' = current image loaded
var data1 = OCRAD(c);
console.log(data1);
}
var im = new Image();
im.onload = imageLoaded; // set onload before src
im.crossOrigin = 'anonymous'; // request CORS usage before setting src
im.src = "message.png";
If a request will work is entirely up to the server which may deny the request (which is default behavior in most cases).
In that case only moving the image or setting up a proxy page to load the external image will allow usage of it. Note that file:// or local files are considered different origins.
A proxy page is in essence a page you pass the image url to as an argument. The page will then, on server side, load the image and pass the data back to your first (requesting) page. This way you can "stream" the image through your own server removing CORS restrictions but at the expense of increased traffic on your own server. Some server may also block this approach by denying external access (ie. by referrer or IP etc.)
See Cross-Origin Resource Sharing for more details.