I have this code im using on my website but the image does not load when page opens, I want the image to load from start up then a simple mouse over to change image and a link when clicked. Im not good at coding so any help would be good.
here is the code im using.
<!doctype html>
<html>
<body>
<head>
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }
function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.src = src;
context.drawImage(img, 0, 0, 322, 200);
}
</script>
</head>
No Canvas Support in Browser
You need to wait for the image to load before you draw it. Also, if your browser doesn't support canvas nothing will help you with this approach.
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0, 322, 200);
};
img.src = src;
}
You should wait for the image to load. Thus your code should be (with corrections regarding html markup):
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
</head>
<body>
<canvas id="e" style="width: 100%; height: 100%;"></canvas>
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('http://earthbounds.com/banners/amazing food.jpg'); }
function setImageTwo() { setImage('http://earthbounds.com/banners/amazing food 2.jpg'); }
function setImage(src) {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image;
img.onload = function (){
context.drawImage(img, 10, 10);
};
img.src = src;
}
init();
</script>
</body>
</html>
This only works in browsers that support canvas ex: Chrome(ium)
Also I suggest you read this
Is this the first method you tried? If you are just trying to add an image on a website and a hover over it there is a much simpler way.
First off, instead of using Javascript to create and load an Image, use the HTML <img> tag, example:
<img src="http://earthbounds.com/banners/amazing food.jpg">
Now to add a simple hover image change, this is not the best practice but for an example, and for a single image you can use onmouseover and onmouseout, example:
<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">
Now to make this image a link to another page, or website you use the <a> tag, example:
<img src="http://earthbounds.com/banners/amazing food.jpg" onmouseover="this.src('http://earthbounds.com/banners/amazing food 2.jpg')" onmouseout="this.src('http://earthbounds.com/banners/amazing food.jpg')">
Hope this helps, and keep looking and learning!
Related
I'm new to js and html5 so here's what I'm doing : I'm working on a game that helps in teaching illustrator shortcuts, the firts level consist of 2 canvas one with an already existing image and the other blank and ready for user to draw on, on ctrl + s press(sure I disabled it's default action using jquery) I want to compare the content of those 2 canvas elements. I've found Image similarity api from deepai.org very useful and accurate, but it only accepts url or input="file" content, so I'm trying to find a way to upload (maybe) the drawn canvas as an image to a server and get the url like this : https://server.com/myaccount/images/img1.png and since i only upload one image I can pass that static url to the api in addition to the original image which will also have a static url so hopefully it compares.
I made a solution that works without a server. But I couldn't make it work in an online code repo like jsfiddle. So I put it on my own server for you to check. http://paulyro.com/paul/deepai/
For convenience I put everything in one file. Of course it would make sense to save the JS in a separate file. But I let that up to you.
For explanation: the red square in a black frame is the canvas. I generate two images and add them to the page. Then I send those images to the deepAI server when you press the button. You will only need one generated img, but for testing purpose I made 2.
Let me know if this is what you were looking for. Of course I expect you to adapt this solution to your exact needs ;)
This is the code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>DeepAiDemo</title>
<script src="https://cdnjs.deepai.org/deepai.min.js"></script>
<style rel="stylesheet">
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas1" width="200" height="200"></canvas>
<button name="button" onClick="load()">Press me</button>
<div style="position:absolute;left:400px; top:30px; height: 354px;" id="messages">Result will get here</div>
<script type="text/javascript">
(async function() {
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
// create green canvas and make it an image
ctx.fillStyle = "green";
ctx.fillRect(75, 75, 50, 50);
var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);
// create red canvas and make it an image
ctx.fillStyle = "red";
ctx.fillRect(75, 75, 50, 50);
var img2 = new Image();
img2.src = can.toDataURL();
document.body.appendChild(img2);
})()
const load = async () => {
document.getElementById('messages').innerHTML = "Waitng for response...";
deepai.setApiKey('xxxxxxxxxxxxxx');
var images = document.getElementsByTagName('img');
console.log("amount images: "+images.length);
console.log(images[0]);
console.log(images[1]);
var resp = await deepai.callStandardApi("image-similarity", {
image1: images[0],
image2: images[1],
});
console.log("response: ");
console.log(resp);
document.getElementById('messages').innerHTML = "Distance: " + resp.output.distance; //resp.output.distance contains the number from the server.
};
</script>
</body>
</html>
Cheers,
Paul
why my page has a lot of empty space between buttons and canvas. when I upload some image
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>uploader</TITLE>
</HEAD>
<body>
<input type="file" name="img" id="uploadimage" size="1">
<a id="downloadLnk" download="img.jpg">download</a>
</p>
</td>
<script>
function draw() { //upload
var ctx = document.getElementById('canvas').getContext('2d'),
img = new Image(),
f = document.getElementById("uploadimage").files[0],
url = window.zURL || window.URL,
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
var parkBg = new Image(600, 500);
document.body.appendChild(parkBg);
parkBg.src = src;
}
}
function download() { //upload
var dt = canvas.toDataURL('image/jpeg');
this.href = dt;
};
downloadLnk.addEventListener('click', download, false);
document.getElementById("uploadimage").addEventListener("change", draw, false)
</script>
<canvas id="canvas"></canvas>
</body>
</html>
The empty space you are seeing is in fact canvas element - without CSS styling it is invisible.
You are not displaying image on canvas - You are adding image element to the document and in it displaying uploaded image.
I suspect You need to display image on canvas.
See my example that accomplishes exactly that: https://jsfiddle.net/hxfp39wo/1/
I wrote a few lines of code to draw an image but seems like it keeps on loading, I tried some W3 School code using the basic implementation but that works fine.
What is happening here is it looks like its stuck in some invisible loop and unable to draw an image.
<script>
var canvas=null;
var context=null;
setup=function(){
canvas=document.getElementById("my_canvas");
context=canvas.getContext('2d');
canvas.width=1200;
canvas.height=720;
img=new Image();
img.onload=onImageLoad;
img.src="http://imgge.bg.ac.rs/images/logo1.jpg";
context.drawImage(img,192,192);
};
onImageLoad=function(){
document.write("done !!");
context.drawImage(img,155,10);
};
setup();
</script>
I replaced your document.write() with a console.log() and it works fine:
var canvas = null;
var context = null;
var setup = function() {
canvas = document.getElementById("my_canvas");
context = canvas.getContext('2d');
canvas.width = 1200;
canvas.height = 720;
img = new Image();
img.onload = onImageLoad;
img.src = "http://imgge.bg.ac.rs/images/logo1.jpg";
context.drawImage(img, 192, 192);
};
onImageLoad = function() {
console.log("done !!");
context.drawImage(img, 155, 10);
};
setup();
<canvas id="my_canvas"></canvas>
For the reason why document.write() causes the canvas to not be displayed, read document.write() overwriting the document?
You might notice a difference between the first and consecutive runs due to img being cached by your browser. A cached image is immediately available for drawing within the setup() function.
First you don't need to write context.drawImage(img,192,192); two times only write inside the image.onload() function. when you write anything using using document.write("Done !"); , it will write the content on this document(HTML) page and may create problems. Instead of that write message on <p> tag instead of on whole document.
here is a snippet for your code:
var canvas=null;
var context=null;
setup=function(){
canvas=document.getElementById("my_canvas");
context=canvas.getContext('2d');
canvas.width=1200;
canvas.height=720;
img=new Image();
img.onload=onImageLoad;
img.src="http://imgge.bg.ac.rs/images/logo1.jpg";
//context.drawImage(img,192,192);
};
onImageLoad=function(){
context.drawImage(img,155,10);
document.getElementById("report").innerHTML="Done !";
};
setup();
<canvas id="my_canvas"></canvas>
<p id="report"></p>
I'm developing hybrid javascript app for android using cordova.
In the following code I use two ways of drawing image on canvas: with setTimeout and without.
Following code (wrapped with cordova) on android device doesn't react on func1 but does react on func2. The second click on func1 finally draws image on a canvas.
Which is completely strange.
I assume it has something to do with android device performance because on my desktop PC both functions works fine.
Why this happening? How to avoid using setTimeout?
<html style="background: white;">
<head>
</head>
<body>
<button onclick="func1()">render img2 func1</button>
<button onclick="func2()">render img2 func2</button><br />
<canvas id="canv">canv</canvas>
<script>
var img = new Image();
var canvas = document.getElementById('canv');
canvas.width = 100;
canvas.height = 100;
var ctx = canvas.getContext("2d");
function setSrc() {
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAASUlEQVRo3u3PAQ0AIAwDsIGC+TcLLkhOWgddSU6Ga5udT4iIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIi8cQEjUgGTmE6z3QAAAABJRU5ErkJggg=="
};
function drawImg() {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
function func1() {
setSrc();
drawImg();
};
function func2() {
setSrc();
setTimeout(function () {
drawImg();
}, 500);
};
</script>
</body>
</html>
It's not so strange as image loading is asynchronous. You are trying to draw the image before it has loaded. On the second click the image has loaded so therefor it will be drawn.
You need to use a callback mechanism in order to make this work:
function setSrc(callback) {
img.onload = callback; /// when image is loaded this will be called
img.src = 'data: ...snipped...';
};
function drawImg() {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
Then modify your function slightly:
function func1() {
setSrc(drawImg); /// drawImg is now callback function for setSrc.
};
Note: if you need to for example draw things on top of the image you must continue your code from the callback function. For example add a callback also for the drawImg function which calls the next step in the code after the image has been drawn. This is because as mentioned, image loading is asynchronous and if you attempt to draw anything else before the image has been loaded the image will be drawn on top instead
The code runs with no bugs, but a problem I am having is because the ".onLoad" function makes it display after the text has already been displayed on the screen. The problem I am facing is that I would like if the text (Loading graphics and loading variables) displayed over the image.
The code is here:
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml1-transitional.dtd">
<html>
<body>
<canvas id="ctx" width="800" height="500" style="border:1px solid #d3d3d3;"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
var canvas = document.getElementById('ctx');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
};
imageObj.src = 'img/startscreen.jpg';
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
</script>
</body>
</html>
I would layer the background image on its own canvas positioned behind the text layer. Then you can clear and update the text layer without having to re-draw the background image.
#background,#overlay {
position: absolute;
}
<canvas id="background"></canvas>
<canvas id="overlay"></canvas>
var can = document.getElementById('overlay'),
bg_can = document.getElementById('background'),
height = can.height = bg_can.height = 500,
width = can.width = bg_can.width = 500,
ctx = can.getContext('2d'),
bctx = bg_can.getContext('2d');
var img = new Image();
img.src = ' ... ';
img.onload = init;
function init() {
// draw the background
bctx.drawImage(this, 0, 0);
// draw your initial text
updateText('hello world');
// other stuff that is going to take time
updateText('done');
}
function updateText(msg) {
ctx.clearRect(0, 0, width, height);
ctx.fillText(msg, 50, 100);
}
This isn't very well thought out (my code example) for re-use purposes.. but I don't know much about your other needs :) hope this helps.
If you want to overlay String on image, why don you use image as backGround imange and place text over it??
Css
try in css
#ctx{
background-image:url('img/startscreen.jpg');}
remove image source in script or insert css in script itself
Css in scripts
ctx.style.backgroundImage=url('img/startscreen.jpg');
I called the function for the text to be displayed after the background has:
imageObj.src = 'img/startscreen.jpg';
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
init()
};
function init(){
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
}