the desired behavior is when the document loads, canvas draws image 0. when the invisible div is clicked, canvas draws image 1, on mouseup or mouseout, it reverts back to image 0.
I left the css out because I got that working...just need to know what I'm doing wrong with the javascript function. right now it doesn't display anything, not even the first image.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function imgChange(imagePath)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath; <!-- I THINK THIS IS WRONG?
</script>
</head>
<body>
<canvas id="myCanvas" width="506" height="319"
onload="imgChange('0.gif')" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<div id="button1" onMouseDown="imgChange('1.gif')" onMouseUp="imgChange('0.gif')" onMouseOut="imgChange('0.gif')"></div>
<div id="key2"></div>
</body>
</html>
your code is missing an ending block
function imgChange(imagePath) {
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src=imagePath;
}
The last '}' is missing
JavaScript looks good. But you can't click on an invisible div. Make the div visible and try.
Be aware of same origin policy too. Image path should be in your domain. If you are running in localhost you might need to have a local HTTP server.
Related
I know this question has already been asked several times, however, I haven't
found a solution yet.
I want to take an image, rotate it and put it in a HTML canvas, to do this I'm using another canvas in which I rotate the image, this part works well, however, when I try to take the image from the second canvas using .toDataUrl, it returns a blank image. The code is the following
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id=canvas height="400" width="400" style="border: 10px solid orange"></canvas>
<canvas id=canvasTransform height="183" width="183" style="border: 10px solid orange"></canvas>
<script type="text/javascript">
//this is the canvas in which I want to put the rotated image
var canvas=document.getElementById("canvas");
var context=canvas.getContext("2d");
//and I use this one to rotate it
var canvasTransform=document.getElementById('canvasTransform');
var contextTransform=canvasTransform.getContext("2d");
var image=new Image(46,183);
image.onload=function(){
contextTransform.drawImage(image,0,0);
}
image.src="Fireball.png";
console.log(image.src);
//Now I rotate the context
contextTransform.rotate(-0.25*Math.PI);
//After doing this, I can see the rotated image in the second canvas, however, the following line returns a blank image
var rotatedImageURL=canvasTransform.toDataURL();
console.log(rotatedImageURL);
//Finally, this part isn't wornking since I just draw a blank image
var rotatedImage=new Image();
rotatedImage.onload=function(){
context.drawImage(rotatedImage,0,0);
}
rotatedImage.src=rotatedImageURL;
</script>
</body>
</html>
I have been stuck here for a while, so any help is appreciated. Thanks in advance!
You likely need to wait until after drawing the image before calling toDataURL. The fireball is only drawn after the image is loaded but the rotate (and everything after that) is called right after registering the onload event handler (but before it has actually loaded).
I'm just trying to figure out how to get an image to draw on a canvas. I followed a tutorial on W3 schools, but when i tried it on my own it doesn't seem to be working. I copy and paste the code below into an HTML file, and the image never loads into the canvas. I downloaded the picture into the same directory. I've been asking around, and looked online, but no one seems to know what the problem is.
I'm using an updated version of chrome (Version 29.0.1547.76 m).
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">
<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
this.ctx.drawImage(img,10,10);
</script>
</body>
</html>
Your image probably hasn't finished loading at the point you are using drawImage:
HTML
Add onload handler in img tag:
<img id="scream" onload="draw()" src="...
Then the function to handle it:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
function draw() {
ctx.drawImage(img,10,10);
}
Online demo here
Be aware of that where you place the scripts in your document matters as well.
I would recommend you setting the src attribute in JavaScript as well. That makes it more "safe" to handle the onload (or subscribed event with img.addEventListener('load', ...).
you should use the following approach that first let the image loaded then display:
image.onload = function() {
pic.getContext('2d').drawImage('your image to display', 0,0);
}
"If you try to call drawImage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don't try this before the image has loaded."
example:
var img = new Image(); // Create new img element
img.addEventListener('load', function() {
// execute drawImage statements here
}, false);
img.src = 'myImage.png'; // Set source path
Source
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
canvas drawImage doesn't draw images the first time
I have made an web application in which I have made a game, the game doesn't work on first load, it only runs when you refresh the page, on mozilla or chrome it starts again (i.e is normal). the code is as follow:
<!DOCTYPE html>
<html>
<head>
<script>
function init() {
img=new Image();
img.src= "Device-Android.png";
img1= new Image();
img1.src= "background.png";
play=new Image();
play.src="play.png";
canvas1 = document.getElementById('canvas');
//alert("show");
if (canvas1 && canvas1.getContext) {
ctx = canvas1.getContext('2d');
ctx.drawImage(img,0,0,394,726);
ctx.drawImage(img1,37,92,317,477);
ctx.drawImage(play,149,300,70,40);
//alert("show somthing");
ctx.font = "bold 15pt sans-serif";
document.onmousedown = initGame;
}
}
................ remaining functions
</script>
</head>
<body onload="init();">
<center>
<canvas id="canvas" width="387" height="700"> <h1>Memory Game</h1> </canvas>
</center>
</body>
</html>
It may be that your images are not completely loaded when you try to draw them.
When you onload=init(){image.src="...";} it is the image.src call that starts loading the image. If you are immediately drawing to canvas (a few lines later) it isn't done loading yet. When you reload the page then it is in the cache from last page load.
Write a pre-loader. Or load those images before calling init().
There is a variable to tell you if an image is done loading. I think it is image.complete
Here is my code:
<body>
<canvas id="myCanvas" width="1100" height="600" style="border:1px solid #c3c3c3; cursor:move">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.src="image.jpg";
img.id="im";
img.onload = function(){
ctx.drawImage(img,0,0,100,100);
autoRun();
};
function autoRun(){
ctx.clearRect(0, 0, 1100,600);
img.id="im";
ctx.drawImage(img,Math.floor((Math.random()*1000)+1),Math.floor((Math.random()*500)+1),70,70);
setTimeout('autoRun()',1000);
}
</script>
</body>
Here I am using the random method for setting the X and Y coordinates hence the image will move dynamically will move the area of canvas ...
setTimeout('autoRun()',1000);
The above line will call the autorun function javascript for every sec and that function will clear the canvas and redraw the image with new coordinates....
Now i would like to get the id of the image when we click on it. How can I do that?
EDIT- This would not work !
Should this work for you ? Or are there any other complications ?
//This would bind to all image, but you can use
//other jquery selectors to select your perticular
//image
$('img').click(function(){
var my_id = $(this).attr('id');
return false;
});
EDIT
"..The image itself is not available in the DOM, you just created it temporarily to draw it into the canvas. So the canvas holds the content of the image, the image itself is not in the DOM"
Select image within canvas with jQuery
I think you should segment the shape of your image (defining its boundary pixels) and then check if when you click inside the canvas, the point selected (the mouse position when clicking) is inside the image shape.
This can be a solution for your problem.
Please help me:
create clickable regions in the canvas below that I can assign onmousedown= events to. I know how to do this with invisible DIVs, but I think there is a more elegant way to do it in canvas that I don't know.
when I click one of the regions, want to pass an image name to a function so that it changes the image being displayed to another image, and then changes it back onmouseup.
if you show me just one region and one mousedown/mouseup example I can do the rest...thanks.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="506" height="319" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
};
img.src="firstImage.gif";
</script>
/////////HERE NEED/////////
CREATE CLICKABLE REGION <region>
<region>
onmousedown=changeCanvasImage(secondImage.gif) //change image on click
onmouseup=changeCanvasImage(firstImage.gif) /change it back when done
</region>
</body>
</html>
The canvas element can fire events but graphical elements within the canvas cannot. To do this you'll either need to implement it yourself by detecting the position of the mouse on the canvas when it is clicked and relating the value to something in your canvas, or using one of the many canvas libraries available which will handle the detection for you.