I am trying to load an image inside a function, but the image is not showing on the screen. There are no console errors so i don't know why it will not work.
Code:
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var score = 0;
var menuImg = new Image();
menuImg.src = "images/Startscreen.png";
gamemenu();
//The menu screen
function gamemenu(){
ctx.drawImage(menuImg,0,0);
}
The image should draw when the function is called but it does not, any help?
Loading an image is an asynchronous process so you need to add an event handler for the "load" event.
menuImg = new Image();
menuImg.addEventListener("load", function () {
gamemenu();
}, false);
I deal with this on a regular basis in my projects since we make heavy use of canvas and sprite rendering.
Update: Here's MDN's page about this topic.
Related
I am having trouble trying to resize the uploaded image on to my html for project. When I searched for a solution. The site https://www.w3schools.com/tags/canvas_drawimage.asp gave me an idea but I can't seem to wrap my head about the script. Am I misunderstanding something about the script?
<javascript>
function uploadForegroundImage(){
fileInput = document.getElementById("foregroundImageUpload");
image = new Image(fileInput);
image.onload = function() {
var c = document.getElementById("foregroundImageCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById(fileInput);
ctx.drawImage(img, 10, 10, 600, 400);
}
}
</javascript>
The code provided should work. If you are getting an error, make sure to load it from a URL that you have access to, or select it using an HTML input tag. Also I'm not aware of a "javascript" tag, it should be changed to "script"
I have an upload photo button on my website which uploads jpeg and png format files on the database.As well as it shows the photo on the website after successful completion.
After successful completion, ajax success calls the after_success function which has the response data as its parameter.
Function Looks like this:
function after_success(data){
}
Response Data Looks like:
<img src="uploads/56dda66be0181.png">
Whatever image comes up from this response I was trying to draw it on the canvas.
My Solution:
var canv=document.getElementById("output");
var ctx=canv.getContext("2d");
var canimg=($('img',data));
ctx.drawImage(canimg,10,10);
But this didn't seem to work.How do i get the image on this canvas element?
Note:
Using Div element and jquery .html() it does show the image inside the Div element.
Ok, if I understand correctly, from response of an upload you'll get an image tag, you want to draw the same image on to a canvas with the id output.
Breaking down -
1. you gave to get the image url from the src of the img tag you are getting as response.
2. You have to draw it on to output
var after_success = function(data){
$('.someHiddenDiv').append(data);//append the response data to some div which is invisible. This is just to get jQuery to access the element as dom.
var img = new Image();//well initialize a new image
//on load of the image draw it on to canvas
img.onload = function(){
var canvas = document.getElementById('output');
var ctx = canvas.getContext('2d');
ctx.drawImage(img,10,10);//same as what you have done
};
img.src = $('.someHiddenDiv').find('img').attr('src');//get source from the image tag
}
This should work!
function after_success(data){
$('#hiddendiv').html(data);
var img=new Image();
img.src=$('#hiddendiv').find('img').attr('src');
$('#hiddendiv').hide();
var canv=document.getElementById("output");
var ctx=canv.getContext("2d");
img.onload= function () {
ctx.drawImage(img,10,10);
}
This is what i did to achieve the same.Thanks to #anubhab.Gave me a fair Idea as to how to do this.Just tweaked his code a bit.
I am using chartjs which is HTML5 based library, to dynamically draw a chart inside a Bootstrap modal body. Everything is fine and I can see the correct data and label array has been passed, and canvas HTML node has been created, but I am getting this error:
Uncaught TypeError: Cannot read property 'offsetWidth' of undefined
I thought maybe I am calling this function too early:
new Chart(--> HTML node <--).get(0).getContext("2d").Bar(--> data <--);
so I put it in setTimeout() block to call the function after like 2 seconds of appending canvas HTML node, but I am still getting that error and not able to see the chart.
Here is the complete code (github, Dropbox) and here is the part I am calling the chart libraray:
document.getElementById("modalBody").appendChild(canvasElement);
setTimeout(function () {
var ctx = document.getElementsByTagName("canvas")[0];
var myNewChart = new Chart(ctx).get(0).getContext("2d").Bar(finalData);
return finalData;
}, 2000);
I managed to get this working in Plunkr.
The basics of what I changed for both contextualizeForType2() and contextualizeForType3() are as follows:
The correct way to instantiate the bar chart component is using the 2D context for the canvas element you appended. In code, you have new Chart(ctx.getContext('2d')).Bar(finalData); after the var ctx = ... line. However, because the modal hasn't been shown yet, it will have a height and width of 0.
To have the chart use the correct height and width, you should bind to the shown.bs.modal event that gets triggered once the modal has finished animating in. Inside that event handler is where you create the chart. The tricky part comes because you have two different questions reusing the same modal. So I added an extra namespace of .typeX, which I unregister my events for when the modal gets hidden.
I know that second point is confusing, but hopefully the code clears it up:
var ctx = document.getElementsByTagName("canvas")[0];
$('#myModal').on({
'shown.bs.modal.type2': function() {
new Chart(ctx.getContext("2d")).Bar(finalData);
},
'hidden.bs.modal.type2': function() {
this.off('.type2');
}
});
This means that once the modal gets hidden, these two functions won't get run again when the same modal is shown for the other type. Additionally, you won't be creating more charts than you need, due to adding a new handler every time the button is clicked.
Alternative method
I had a further play and found that I could refactor the code into a single function that can be called from both contextualizeForType2() and contextualizeForType3(), passing in the finalData. This has the advantage of leaving all the canvas and chart initialisation code in one place, simplifying your large functions somewhat and making it easier to maintain.
The function is:
function showModalChart(data) {
var canvasElement = document.createElement("CANVAS");
canvasElement.setAttribute("width", "400");
canvasElement.setAttribute("height", "400");
document.getElementById("modalBody").appendChild(canvasElement);
var ctx = document.getElementsByTagName("canvas")[0];
$('#myModal').off('.modalchart').on('shown.bs.modal.modalchart', function () {
new Chart(ctx.getContext('2d')).Bar(data);
});
}
I'm trying to work out how to determine when an svg image has loaded in the browser. I'm using Raphael JS and I've tried:
var image = paper.image(path, 0,0,10,10);
image.node.addEventListener('load', function(){alert("test");});
and:
$('image').on('load')
all to no avail. I've also used "onload" and "onsvgload" none of which work.
Is there away to determine if an svg image has actually loaded?
I even tried loading the image using an Image() object and then calling paper.image() - but I get two calls to the image (instead of using the preloaded image);
ie:
var preload = new Image();
preload.src = imgPath;
preload.addEventListener('load', function () {
image.path = preload.src;
//Now load image in raphael - except this still forces the browser to make another call for the image
});
Any ideas?
Using the onLoad event handler works, with one additional line of code:
var image = paper.image(path, 0,0,10,10);
var image_node = image.node;
image_node.setAttribute('externalResourcesRequired','true');
image_node.addEventListener("load", function() {
console.log("image is loaded!");
})
You need to set the externalResourcesRequired attribute to true. You may read more about it here: http://www.w3.org/TR/SVG/struct.html#ExternalResourcesRequired
I have a form element in my HTML page that currently retrieves the toDataURL() from one canvas(canvas2) and draws the image into a second canvas(outputCanvas). What I need is for that onclick event to retrieve the canvas image and use that image in this function. As of now Im able to manually save the canvas image as a .png and then hard-code the file into this function, but I need this all to happen when the button is clicked. Im a newb at .js but I can handle pseudo-code if its easier to explain, but please be specific. The following draw() needs to be handled when the click occurs. I have the listener below that should call the draw().
function init () {
canvas = document.getElementById('anotherCanvas');
ctx = canvas.getContext('2d');
draw ();
}
function draw() {
img = new Image();
img.src = 'recursed1.png';
fr1 = makeFrame(ctx,makeVect(400,0), makeVect(400, 0), makeVect(0, 400));
img.onload = function(){
ctx.save();
newPainter = cornerSplit(imagePainter,5);
newPainter(fr1);
ctx.restore();
ctx.save();
newPainter(flipHorizLeft(fr1));
ctx.restore();
ctx.save();
newPainter(flipVertDown(fr1));
ctx.restore();
ctx.save();
newPainter(flipVertDown(flipHorizLeft(fr1)));
}
The following is currently independent of the above, I can only get the above function to work if I manually save & hard-code the image created in an independent canvas (canvas2). I need the two to work together. The HTML element:
<input type="button" id="recImage" value="Recurse Image">
var formElement = document.getElementById("createImageData");
formElement.addEventListener('click', createImageDataPressed, false);
function createImageDataPressed(e) {
var imageDataDisplay = document.getElementById("imageDataDisplay");
imageDataDisplay.value = canvas2.toDataURL();
var newImagewindow.open(canvas2.toDataURL(),
"canvasImage","right=300,top=400,width="canvas2.width + ",height=" +
canvas2.height + ",toolbar=0,resizable=0");
}
The above is my most recent attempt, it doesn't work... Nothing is set in stone, and If there is a better route than what Im attempting please let me know. this work in progress may help you understand what Im trying to do
From my understanding, you want init and data to be called when formElement is clicked, right?
Just add a call to init and data in createImageDataPressed or add some more click handlers to formElement.