canvas does not draw image on load - javascript

I started to play with canvas coding and I'm stuck on a (most likely) very easy issue. I have a code which on click lads some image, and I would like to put the image on canvas when it's loaded. When I go to diagnostic tools in Chrome, the pictures get loaded and there is no errors in the console, yet the images do get drawn on the canvas.
any ideas why?
sAlphaF = new Image();
sAlphaF.src = '/img/sAlpha_'+tbaID+'_f.png';
sAlphaF.onload = function(){
var ctxs=gc.getContext("2d");
ctxs.drawImage(sAlphaF,0,0, gc.width, gc.length);
};
tAlphaF = new Image();
tAlphaF.src = '/img/tAlpha_'+tbaID+'_f.png';
tAlphaF.onload = function(){
var ctxt=bc.getContext("2d");
ctxt.drawImage(tAlphaF,0,0, bc.width, bc.length);
};

Change your bc.length property to bc.height ;)

Related

Determine when canvas content is loaded

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

Best way to get new Image in Javascript using canvas

I am making a game with the html5 canvas and I am having some trouble getting the images on screen.
//player img
var img1 = new Image();
img1.onload = function() {
console.log("image loaded");
};
img1.src = "player.png";
The image is a .png file called "player" and is saved on my desktop. Am I doing something wrong when setting the src method? Is there a better way to do this? I appreciate any help.
Well first, the image should have a path that is relative to the html document and if you are not seeing the image, it's probably because you didn't put that relative path into your code (you are only using the file name which implies the image is in the same directory as the html file).
Also, you haven't shown any code to associate the image with the canvas. This is the approach:
// Get the DOM object reference for the canvas element:
var canvas = document.getElementById("canvas");
// Get an object reference for the canvas' contextual environment:
var ctx = canvas.getContext('2d');
// Instantiate an image to use as the background of the canvas:
var img = new Image();
// Make sure the image is loaded first otherwise nothing will draw.
img.addEventListener("load", function () {
// Draw the image on the canvas at position 0, 0 (top-left):
ctx.drawImage(img, 0, 0);
});
// Wait until after wiring up the load event handler to set the image source
// This example assumes that the image is located in a sub-folder of the current folder, called images.
// Your path must be a relative reference to the location where the image is.
img.src = "images/starfield.jpg";

Chrome will not display "new Image()" in canvas

Beginner dev here. One of my lessons is to place (and transform) an image into canvas using only the Image() constructor. That is to say, NOT creating a variable that is linked to an image element located in the HTML code. Consider the following:
<script type = "text/javascript">
function draw(){
var drawing = document.getElementById("drawing");
var con = drawing.getContext("2d");
var dog = new Image();
dog.src = "dog.jpg";
//begin transformation
con.save();
con.translate(200, 100);
con.rotate(25*Math.PI/180);
con.drawImage(dog, 0, 0);
con.restore();
}
</script>`
I used some CSS to outline the canvas in red and move it closer to the center of the screen for visibility's sake. Despite all my efforts, Chrome will not display the image, but IE will. However, IE does require a prompt for the image to show: "Internet Explorer restricted this webpage from running scripts or ActiveX controls." After allowing this with the button that they provide, the image displays.
Chrome, on the other hand, does not provide a prompt of any kind. I've looked around extensively for an answer to this and even went so far as to enable/disable all the script running options and extensions (popups and downloads included) to no avail.
Just to be clear, I'm aware that there are other ways for the image to display properly, but my concern is for why it won't work with Chrome in this context.
Your code is not waiting for the image to load:
var drawing = document.getElementById("drawing");
var con = drawing.getContext("2d");
var dog = new Image();
//begin transformation
dog.onload = function() {
con.save();
con.translate(200, 100);
con.rotate(25*Math.PI/180);
con.drawImage(dog, 0, 0);
con.restore();
};
dog.src = "dog.jpg";
By putting the image copy code into the "load" handler, you ensure that the image pixels are actually available. There's no significant performance penalty to pay if the image happens to already be in the browser cache.

Would drawing an image to a canvas be described as hotlinking if the image was from another site?

If you created an image object like so:
var imageObj = new Image();
imageObj.src = urlOfImageOnAnotherWebsite;
And then drew it to a canvas on my website like so:
var canvas = document.getElementById('cnv');
var context = canvas.getContext('2d');
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
drawText(statusquote,date);
};
Would this be hotlinking the image? I initially am thinking no because I'm actually redrawing the image, and not hosting it.
Yes, the principle is the same. You are loading it from another domain.
Hotlinking is the act of using someone else's server and bandwidth to display content to your viewers. Since in this scenario the JavaScript still obtains the image from their site, it's hotlinking.

canvas is cleared on mousedown, sketch.js & jquery 2.0.0

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?

Categories

Resources