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"
Related
I would like to get this effect working on my webpage.
But I already tried this multiple times and failed every time. So, this is the reason why I am going to try it first on a local level. I copied everything you can see on the codepen.io webpage and replaced the both images with my pictures. Further, I added the id id="coverart" to the img and thats it.
But I get an error on this:
if (image.complete) {
The reason for it is:
Cannot read property 'complete' of null
But if I type this in my console:
document.getElementById('coverart');
I get the element back:
<img id="coverart" src="https://gamekeys-shop.de/wp-content/uploads/2017/01/coverart.png">
So, it cannot be null... What could be the reason for it and how can I fix it?
Here you can download the little html, css and js files.
EDIT:
If you insert alert(image), you will get null. If you replace this
if (image.complete) {
start();
} else {
image.onload = start;
}
with this
image.onload = start;
You will get the same null error... Why do I get null... It cannot be null?
There are few possible ways to improve it:
1) Just put your javascript file after the img tag.
2) Or run you code only when document will be loaded.
You can put your jquery definition onto bottom of body tag and use jquery $(document).ready() event like following.
$(document).ready(function(){
var image = document.getElementById("coverart");
if(image.complete){
console.log("loaded");
}
})
<img id="coverart" src="http://via.placeholder.com/350x150"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Since there is no need to wrap your code within a $(document).ready(function(){...}); or $(function(){...}); on codepen.So try doing that. You need jQuery to do that. So just add
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
to your HTML head.
$(document).ready(function(){
var image = document.querySelector('img');
var imageCanvas = document.createElement('canvas');
var imageCanvasContext = imageCanvas.getContext('2d');
...
imageCanvasContext.drawImage(image, 0, 0, width, height);
imageCanvasContext.globalCompositeOperation = 'destination-in';
imageCanvasContext.drawImage(lineCanvas, 0, 0);
}
});
Tried that for myself on localhost and it's working fine
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'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 been mucking about with a little bit coding using jquery and canvas (not together).
I have an external javascript file and in it contains;
$(document).ready(function() {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy',];
var rosie = ['Mum',];
var prev;
$('button').click(function() {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
});
I also have some inline javascript which is for the canvas element;
<script>
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
</script>
When separated by using inline javascript for the canvas and an external file for the jquery everything works fine and as expected.
When adding the inline canvas javascript to the external file the canvas element is not working but the jquery is. The javascript is loaded after the canvas element as my external javascript is linked just before the closing body tag and furthermore if I remove all jquery from the external file the canvas element begins to work again.
Why is this?
Thanks
EDIT
I have also now tried putting the canvas code inside jquerys document ready function and outside of it and it is still not working. I have wrapped the canvas code in an anonymous function still to no avail and have even tried selecting the canvas element with jquery itself like below;
var canvas = $('canvas')[0];
But it still doesn't want to know. Putting the canvas code before all the jquery then the canvas code executes but the jquery doesn't, I really am baffled! It doesn't bother me keeping it seperate but I would like to know why it is happening.
Thanks again.
This simple problems could be noted if you use the Browser Console. That's it! You can open the console pressing Ctrl+Shift+J:
In home page:
Error: Uncaught ReferenceError: $ is not defined
Solution: Link jQuery in your source
In namechooser page:
Error: Uncaught TypeError: Cannot read property 'getContext' of null
The problem:
You are trying to manipulate a div as it was a canvas, and you can't get the context of a div element. So this is your HTML:
<div id="wrap">
<h1>PORTFOLIO PROJECT :)</h1>
<button>Click here to generate a company name!</button>
</div>
Solution:
Change <div> for <canvas>
How to avoid future problems like this?
Use the browser console, that's it!
Ok, if I combine the code you have, above, it should look something like this: (see my jsFiddle for full context : http://jsfiddle.net/mori57/TqamB/ )
$(document).ready(function () {
/*
NAME CHOOSER
*/
var carl = ['Sha', 'Shads', 'Cai', 'Moon', 'Sun', 'Staffy'];
var rosie = ['Mum'];
var prev;
$('button').click(function () {
prev = $('h2').text();
$('h2').empty().text(carl[Math.floor(Math.random() * carl.length)] + rosie[Math.floor(Math.random() * rosie.length)]).after('<p>' + prev + '</p>');
});
var canvas = document.getElementById('draw');
if(canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 800, 500);
}
});
And, running within the context of jsFiddle, this works perfectly.
So, either you're not combining the two scripts properly (putting the canvas outside the document-ready block, for example, or somehow missing a closing brace), or there's something else amiss in your script file or markup.
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.