I'm new to this - I just can't figure out why this isn't working. When I remove Display:none from HTML, the image works correctly so I know the path to the image is correct. But it's not drawing on the canvas. Thanks for your time.
HTML:
<canvas width="840" height="900" id="Canvas6">
Your browser does not support this feature.
</canvas>
<img src="image/logo.png" id="img1" width="825" height="272" style="display:none;">
<script type="text/javascript" src="js/main.js"></script>
Main.JS JAVASCRIPT:
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
//Create a variable to hold our image
var srcImg = document.getElementById("img1");
//Draw an image directly onto the canvas
ctx.drawImage(srcImg, 0,0);
//Draw a scaled down image
//drawImage(srcImg, dx, dy, dw, dh)
}
}
In html file, the first best thing you have done is used the 'script' tag right at the end of the html file.
This ensures that the "Critical Render Time" is minimized, and the display items in HTML are shown first. (Not a huge impact on this case, because here you are using the JS to draw/display, but this approach is really good when you use your js for other purposes like calculations etc., and you don't want to stop the other HTML items from displaying because of an ongoing calculation.)
Now that the canvas is ready, its time to throw the image on the canvas.
Try using the border property (style="border: 2px dotted black") to see the container area of the canvas.
Hmmm !! But the image doesn't show in canvas. WHY ??
Images(or any other files) take atleast some time to get processed. By the time they are getting processed to be loaded on the screen, your canvas is already getting displayed. Hence you see an empty canvas.
So, the solution is to make everything else wait, till the time image gets loaded.
How do we do that ? Just use the "Event Listener".
EventListener is the property of Window object. (window.addEventListener("load", some_func_to_run , false);). We generally use this, when we want our window/page/browser to wait for something, but hey , we can use it for our images as well.
var cvs = document.getElementById("canvas"); // Getting the control of the canvas
var ctx = cvs.getContext("2d"); //Getting the control of the useful HTML object getContext . This object brings in a lot of useful methods like drawImage, fillRect etc.
//create images
var bg = new Image(); // Creating image objects
bg.src = "images/bg.png"; //Setting the source file
//create images ends
//load images first
bg.addEventListener("load" , draw , false); //**IMPORTANT : Just remove this line and you will start facing this problem of empty canvas again
//loading images ends
function draw() {
ctx.drawImage(bg,0,0); // Putting the image and its coordinates on the canvas
}
draw(); // Calling the draw function to put the image on canvas
<html>
<body>
<canvas id="canvas" width="288" height="512" style="border: 2px dotted black"> </canvas>
<script src="flappyBird.js"></script>
</body>
</html>
So, it all about using Event Listener and asking everything to wait till the image gets loaded.
Hope this help. :)
If you try to place an image on a Canvas before it has loaded, it will not show. It is not like the img tag that will show the image whenever it loads. I surrounded your JS with an onload and it worked for me.
document.getElementById("img1").onload = function() { /* Your JS */ };
You have to wait for the image to load before you can draw it on the canvas, so set your drawing code to run on the window load event (by which time all images are loaded). Also, you don't need to include the markup for the image on the page, where you have to then prevent it from displaying with CSS. You can just create the image object and set the source attribute in the javascript. For example:
var img = document.createElement('img');
img.src = 'image/logo.png';
window.addEventListener('load', function(){
var theCanvas = document.getElementById('Canvas6');
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
ctx.drawImage(img, 0,0);
}
}
});
Related
Is there a way to detect when canvas content is loaded? What I'm trying is following. I need to print a page where in a widget is rendered a pdf document using the pdfjs library. Only the first pdf page have to be printed alongside with the content of the web page where the widget is placed. My approach was to get the canvas of the first pdf page which the pdfjs library created and put its content as source of an img element.
var content = canvas.toDataURL();
var img = document.createElement('img');
img.setAttribute('src', content);
widget.parentNode.insertBefore(img, widget);
Now if I use this as is, the image is created but is blank. If I put the code above inside setTimeout with a few seconds delay the image is rendered properly with the content of the first pdf page but this is not reliable for me. I've checked the content returned by canvas.toDataURL() in both cases and it appeared not equal so this was the reason for my conclusion that the content of the canvas was not loaded yet.
Any ideas for solution would be appreciated.
canvas will bind to the DOM like any other html tag. But your problem is image is not loading at very first time. So use onload method for loading images.
Refer HTML5 Canvas Load Image Data URL
EDIT :
drawImage() method draws an image or video onto the canvas. So use that method to draw the image on canvas.
Here is the updated code:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 10, 10); // here this = image, 10 = width of the image, 10 = height of the image
};
imageObj.src = dataURL;
For more information see here
drawImage canvas method is running before the 'img' element has had a chance to fully load so I need your help o fix this problem.
<canvas id="drawImage" width="900" height="900" style=""> </canvas>
<img id="img" src="images/fb.png"/>
<script type="text/javascript">
var canvas = document.getElementById("drawImage");
var cont = canvas.getContext("2d");
var img = document.getElementById("img");
cont.drawImage(img , 100 , 100);
</script>
I tried this code to draw image , but it does not draw any thing
As I know, you couldn't put any DOM elements in canvas. But you can try putting image in canvas like that
var example = document.getElementById("example"),
ctx = example.getContext('2d'), // context
pic = new Image(); // creating new image
pic.src = 'http://habrahabr.ru/i/nocopypast.png'; //source
pic.onload = function() { // Waiting till load
ctx.drawImage(pic, 0, 0);
} // Draw image when it's loaded
First, your code to draw the 'img' element into canvas is correct.
One problem is that that code is running before the 'img' element has had a chance to fully load.
Therefore, you must tell the browser not to run your javascript until the page elements are fully loaded.
You can tell the browser by wrapping your javascript in window.onload like this:
<script>
window.onload=(function(){
var canvas = document.getElementById("drawImage");
var cont = canvas.getContext("2d");
var img = document.getElementById("img");
cont.drawImage(img , 100 , 100);
}); // end $(function(){});
</script>
Note: Html Canvas is designed to be able to read the pixels in an img-element. Canvas cannot do the same with other canvas elements (you mention a div in your question). There is a plugin script that translates html into canvas drawings: http://html2canvas.hertzen.com/
11I'm using sketch.js from here: http://intridea.github.io/sketch.js/ and jquery 2.0.0
On my page, I have a list of images presented like so:
<img src="http://url.to/image"><br><span class="background">click for background</span>
and a canvas, set up like so:
<canvas id="simple_sketch" style="border: 2px solid black;"></canvas>
relevant JavaScript:
var winwidth = 800;
var winheight = 600;
$('#simple_sketch').attr('width', winwidth).attr('height', winheight);
$('#simple_sketch').sketch();
$('.background').on('click', function(event) {
event.preventDefault();
var imgurl = $(this).parent().attr('href');
console.log('imgurl: ' + imgurl);
var n = imgurl.split('/');
var size = n.length;
var file = '../webkort/' + n[size - 1];
var sigCanvas = document.getElementById('simple_sketch');
var context = sigCanvas.getContext('2d');
var imageObj = new Image();
imageObj.src = imgurl;
imageObj.onload = function() {
context.drawImage(this, 0, 0,sigCanvas.width,sigCanvas.height);
};
alert('background changed');
});
Backgrounds are changed just as I want them to, but whenever I click on the canvas, the backgound image is cleared. As per a suggestion on this thread: html5 canvas background image disappear on mousemove I commented out this.el.width = this.canvas.width(); on line 116 of sketch.js, but to no avail.
Any help appreciated!
EDIT: jsfiddle: http://jsfiddle.net/RXFX4/1/
EDIT: Couldn't figure out how to do this with sketch.js, so instead went with jqScribble (link posted in comments) which has the ability to do this as a built-in function instead.
Find this line on the library - sketch.js and delete/comment it out.
this.el.width = this.canvas.width();
Good luck
Assign the url on the image source after the onload event. If the image is already loaded, the event is probably firing before you are hooking it. Which means that your drawImage is never being called.
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(this, 0, 0,sigCanvas.width,sigCanvas.height);
};
imageObj.src = imgurl;
EDIT: I'm going to take a shot in the dark here, since I'm not familiar with sketchjs
I'm thinking that your problem is that you are completely re-render the canvas when you click your 'change background' link. Notice that if you draw, then click the change background, you lose your drawing.
However, notice that once you click again, the background disappears, and you get your original drawing back again. This tells me that sketchjs is keeping track of what has been drawn on it's own in-memory canvas, and then it drops it onto the target. The problem, then, is that when this in-memory canvas is drawn, it completely replaces the contents of the target canvas with it's own.
I notice in some of the sketchjs examples, if you want a background they actually assign the canvas a background style. In your example, you are drawing the background directly onto the canvas. The prior probably works because sketchjs knows to incorporate the background style when it draws. However, it does not know that when you drew your fresh background image, it should be using that.
Can you just change the background style on the canvas element, instead of drawing directly on the canvas?
So, I'm using this function getImageData on the "context" variable that I've made inside of the <script> part, and when I do something such as draw a rectangle then do ctx.getImageData.data[0] it will show the red value of that rectangle that I drew on the canvas. But, when I import an image and draw it onto the canvas, and try to use the getImageData.data[0] all I get is 0, which makes no sense, I'm not sure why it is not reading the image correctly. I've tried tutorials on this but they're all vague and only have segments written together.
So, when I draw the rectangle, its color value comes out just fine, but again, when I draw the image, even without drawing the rectangle on the canvas, I never get the value of that particular pixel on the image.
Can someone help me? Here's my currrent code:
<html>
<head>
<title>
Color Test :)
</title>
</head>
<body>
<canvas id = "ColorTest" width = "500" height = "500">
please don't use shitty browsers :)
</canvas>
<script>
//netscape.security.PrivilegeManage…
var canvas = document.getElementById("ColorTest")
, ctx = canvas.getContext("2d")
, image = new Image()
image.onload = function(){
ctx.drawImage(image,0,0)
}
image.src = 'Pikachu.gif'
ctx.fillStyle = "rgb(123,40,170)"
ctx.fillRect(0,0,100,100)
var imagedata = ctx.getImageData(0,0,100,100)
, spot = 0
while(imagedata.data[spot] == 0){
spot++
}
console.log(imagedata.data[0])
</script>
</body>
</html>
Does the following alert anything sensible?
image.onload = function() {
ctx.drawImage(image, 0, 0);
var id = ctx.getImageData(0,0,canvas.width,canvas.height);
alert([id.data[0], id.data[1], id.data[2], id.data[3]].join(", "));
}
It could be that the image is transparent. Try with a single color non-transperent image.
What browser are you using? Using getImageData when loading an image from another domain is not allowed (security issue), and if I remember correctly there is some browsers that have problems determining the domain when running scripts localy
I have a html page like this:
<html>
<body>
(1)<canvas id="cs"></canvas>
(2)<img src="/image.png" id="img"/>
</body>
</html>
I would like to know how I could load and display the image (2) in the canvas (1) (with drawImage function).
I tried this but it doesn't work :
var img = $("#img");
ctx.drawImage(img,0,0);
You have to ensure that your image has loaded first. Try wrapping your drawImage call in a ready statment and make certain you are setting up your canvas object first.
$().ready(function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.drawImage(document.getElementById("img"),0,0);
})
If you haven't already found it here is a nice tutorial: https://developer.mozilla.org/en/Canvas_tutorial/Using_images
Is that all of your code?
You need to set up the canvas first:
var ctx = document.getElementById('cs').getContext('2d');
var img = new Image();
img.src=document.getElementById('img').src;
ctx.drawImage(img,0,0);
Something like that...
Here's an example in jsfiddle: http://jsfiddle.net/vTYqS/
Note that the first picture gets cut off because of the default canvas size. Depending on the image you plan to copy, you may need to resize your canvas like this:
http://jsfiddle.net/vTYqS/1/