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
Related
I use canvas to draw an image only, but toDataURL() value is different with raw data even if canvas did not change.
the code as blow:
<html>
<head>
<title>For test</title>
<script type="text/javascript">
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
img.crossOrigin = 'Anonymous';
ctx.drawImage(img, 0, 0);
console.log(c.toDataURL().length);
console.log("data:img/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAzCAIAAAC43dc6AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABPSURBVGhD7dOhAQAgDMAw/n96GCyqZiK5oKZndtPX6Gv0NfoafY2+Rl+jr9HXrO8D/t4nW+lr9DX6Gn2NvkZfo6/R1+hr9DX6Gn3N7r6ZCxmTdxPs4RLCAAAAAElFTkSuQmCC".length);
}
</script>
</head>
<body>
<p>Image to use:</p>
<img id="scream" src="data:img/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAADUAAAAzCAIAAAC43dc6AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABPSURBVGhD7dOhAQAgDMAw/n96GCyqZiK5oKZndtPX6Gv0NfoafY2+Rl+jr9HXrO8D/t4nW+lr9DX6Gn2NvkZfo6/R1+hr9DX6Gn3N7r6ZCxmTdxPs4RLCAAAAAElFTkSuQmCC" /><p>
<p>Canvas:</p>
<canvas id="myCanvas" width="53" height="51"></canvas>
</body>
Simple: you are re-applying the jpeg compression, which is a lossy process. Unless your original image came from a from the same computer, it's a virtually impossibility that they would match exactly. Even if you used the exact same algo, you have to match the quality factor to get a re-encode match. I don't even see the quality being specified in the code (as an argument to toDataURL()).
Even if you used all the same settings, there's a slight bit of voodoo in these encoders, and a device resolution change, zooming, font updates, or a bogged down CPU can all (potentially) affect the output, due to the dynamic nature of canvas layout. Apps like photoshop are much more repeatable than browsers.
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 can't seem to have Chrome browser show the true image size via <img>
and also by drawImage via canvas context. Explorer shows both of these
correctly.
In Chrome, the image shown is not by the dimensions of the original image
but a scaled down one. The browser when rendered from a Web server seems to
have something to do with it. Curiously enough, when open the browser on
the html file locally:
E.g. file:///C:/xampp/htdocs/Website_TEST_active/test1.html, the image dimensions are correct.
Attached is a stripped down HTML and Javascript code. Appreciate any insights.
Thanks
Sean
<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="scream" onload="loadImage()" src="pics/cover.jpg" alt="Test">
<p>Canvas:</p>
<canvas id="myCanvas" width="854" height="480" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
window.onload = function() {
// Not used
}
/*
* Upon image load, draw image on canvas
*/
function loadImage(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 0,0, img.naturalWidth, img.naturalHeight);
console.log("Original Image W=" + img.naturalWidth +
" H=" + img.naturalHeight);
}
</script>
</body>
</html>
I found something that might be right for what you're asking.
Here's the link- https://superuser.com/a/364875
Open Developer tools (Ctrl+Shift+I or use the Settings Icon at the
top-right of your browser window => Tools => Developer tools) and on
the relevant page, switch to the Network tab and reload the page.
In the Size column you'll see the size of everything loaded
(Documents, Stylesheets, Images, Scripts, ...). You can enable a
filter to help you find out what you need - at the bottom-center of
Developer tools frame.
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.
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.