Image not loading on Canvas? - javascript

i'm trying to load an image onto a canvas and hasn't been working after trying everything...
Javascript:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var start = new Image();
start.onload = function(){
context.drawImage(start, 0, 0, start.width, start.height, 0, 0,
canvas.width, canvas.height);
}
start.src = "hangman0.png";
I don't see anything wrong with my code, as I am trying to draw this image and then scale is to the canvas' width and height, but the picture just isn't showing up no matter what. Any pointers? I've tried changing both my HTML5 and css code, still no avail.
CSS:
canvas{
background-color: rgb(0,198,255);
border-style: ridge;
border-width: 5px;
border-color: rgb(157,255,0);
position: relative;
}
HTML5:
<body>
<div id='section'>
<canvas id='myCanvas' width='979px' height='560px'></canvas>
<script src="projectJavaScript.js"></script>
</div>
</body>
Thanks in advance for the help!

Your offered code works for me as long as I use window.onload:
Are you wrapping script code inside window.onload?
<script>
window.onload=(function(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var start = new Image();
start.onload = function(){
context.drawImage(start, 0, 0, start.width, start.height, 0, 0,
canvas.width, canvas.height);
}
start.src = "https://dl.dropboxusercontent.com/u/139992952/multple/rainy.png";
}); // end window.onload
</script>
Example code and a Demo:
Note: StackSnippets automatically wrap JS-script code inside window.onload
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var start = new Image();
start.onload = function(){
context.drawImage(start, 0, 0, start.width, start.height, 0, 0,
canvas.width, canvas.height);
}
start.src = "https://dl.dropboxusercontent.com/u/139992952/multple/rainy.png";
body{ background-color: ivory; }
canvas{border:1px solid red; margin:0 auto; }
<canvas id='myCanvas' width='979px' height='560px'></canvas>

You appear to be setting the image source after it is used which would been it would be using the default blank state when it is called.
You also appear to be using start.onload but start is not element but varble that represents one, it not going to be loaded since it not part of original html elements. I would use canvas.onload or run it with body.onload

Related

How to convert canvas image to standard img? [duplicate]

Is there possibility to convert the image present in a canvas element into an image representing by img src?
I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.
This is my html:
<img src="http://picture.jpg" id="picture" style="display:none"/>
<tr>
<td>
<canvas id="transform_image"></canvas>
</td>
</tr>
<tr>
<td>
<div id="image_for_crop">image from canvas</div>
</td>
</tr>
In JavaScript it should look something like this:
$(document).ready(function() {
img = document.getElementById('picture');
canvas = document.getElementById('transform_image');
if(!canvas || !canvas.getContext){
canvas.parentNode.removeChild(canvas);
} else {
img.style.position = 'absolute';
}
transformImg(90);
ShowImg(imgFile);
}
function transformImg(degree) {
if (document.getElementById('transform_image')) {
var Context = canvas.getContext('2d');
var cx = 0, cy = 0;
var picture = $('#picture');
var displayedImg = {
width: picture.width(),
height: picture.height()
};
var cw = displayedImg.width, ch = displayedImg.height
Context.rotate(degree * Math.PI / 180);
Context.drawImage(img, cx, cy, cw, ch);
}
}
function showImg(imgFile) {
if (!imgFile.type.match(/image.*/))
return;
var img = document.createElement("img"); // creat img object
img.id = "pic"; //I need set some id
img.src = imgFile; // my picture representing by src
document.getElementById('image_for_crop').appendChild(img); //my image for crop
}
How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)
canvas.toDataURL() will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Complete example
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation
Do this. Add this to the bottom of your doc just before you close the body tag.
<script>
function canvasToImg() {
var canvas = document.getElementById("yourCanvasID");
var ctx=canvas.getContext("2d");
//draw a red box
ctx.fillStyle="#FF0000";
ctx.fillRect(10,10,30,30);
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
document.body.appendChild(newImg); // add to end of your document
}
canvasToImg(); //execute the function
</script>
Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Javascript error on webpage console

I am trying to have an image change when you put in a URL and click a button.
But i keep on getting this error:
[object%20HTMLInputElement]:1 GET file:///Users/asbrown/Desktop/MLforSite/[object%20HTMLInputElement] net::ERR_FILE_NOT_FOUND
Here is my code:
$(function() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function drawimg(image) {
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, 400, 300);
}
img = new Image();
img.onload = function() {
canvas.width = 400;
canvas.height = 300;
}
img.src = document.getElementById("newURL");
}); // end $(function(){});
body {
background-color: ivory;
}
canvas {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width=100 height=100></canvas>
<form>
<fieldset>
<legend>Input Data for Training</legend>
<p>
<label>Image URL</label>
<input type="text" id="newURL" value="" />
<br>
</p>
<script>
var newURLF = document.getElementById("newURL").innerHTML;
</script>
<input type="button" value="Add to Training Data" onclick=drawimg(newURLF);/>
Does anyone know which part of my code is causing this error?
I think it has something to do with the way i used the drawImage() function but i don't know what I am doing wrong. Any help would be appreciated.
So there's alot going on here. I'll try and walk you through it.
The ctx.drawImage function can take several objects to draw an image. None of them are a URL however. We first have to create an image object, set the src to be the users supplied URL, then wait for it to load before drawing it on the canvas. (the onload function gets called after the image is finished loading. )
See this for more info in the canvas drawImage function:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
A couple of things to keep in mind.
You have to wait for the image to load before you can draw it on the canvas. This is what the image.onload is doing for us.
You don't need jQuery. I see you're using stuff like document.getElementById. that'll work without jQuery.
Hopefully this is helpful.
function loadImg() {
// setup canvas and 2d context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// get the url entered by the human
var newURL = document.getElementById("newURL").value;
// create an image
var image = new Image();
// this gets run once the image loads
image.onload = function() {
ctx.drawImage(image, 0, 0, 300, 400, 0, 0, 100, 100);
}
// set the image source to the url entered by the user
image.src = newURL;
}
canvas {
border: 1px solid red;
}
<canvas id="canvas" width="100" height="100"></canvas>
<form>
<fieldset>
<legend>Input Data for Training</legend>
<p>
<label>Image URL</label>
<input type="text" id="newURL" value="" />
</p>
<input type="button" value="Load image" onclick="loadImg();" />
</fieldset>
</form>
You need to get the value from the input like this
var newURLF = document.getElementById("newURL").value;

how to load new image and draw it to the canvas?

i have a image and i draw that image on the canvas. now i want to change the source of the image and again draw the image in the canvas.
i have tried the below code and here is the jsfiddler. canvas's drawing is not changing.... what to do?
HTML
<button onclick="change_2_new_image();">change_image()</button>
<img id="test" src="http://static.clickbd.com/global/classified/item_img/374646_0_original.jpg" alt="error" title="This is an image" />
<canvas id="myCanvas" width="320px" height="275px"><canvas>
JS
var img;
$(function () {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
img = document.getElementById("test");
img.ready = function () {
alert("asasas");
};
ctx.drawImage(img, 0, 0);
});
function change_2_new_image() {
$('#test').attr("src", "http://upload.wikimedia.org/wikipedia/en/9/9a/Grameenphone_Logo.png");
img = document.getElementById("test");
ctx.drawImage(img, 0, 0);
}
Your issue is with variable scope. You can't access ctx from the function.
function change_2_new_image() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
$('#test').attr("src", "http://upload.wikimedia.org/wikipedia/en/9/9a/Grameenphone_Logo.png");
img = document.getElementById("test");
ctx.drawImage(img, 0, 0);
ctx.render()
}
The above should now work.
ctx is defined inside of your closure and not defined in change_2_new_image() that's why the error message ReferenceError: ctx is not defined is popping up in the console. After fixing that, you may also notice that the image at times, hasn't yet loaded. use jQuery's on('load', ... ) event. for more info, you can have a look at this thread: jQuery event for images loaded
Hope that helps!

Draw a canvas into another canvas not working

I am trying to draw a canvas created through javascript on another canvas. But it is not working for me,
Here is my code,
<!DOCTYPE HTML>
<html>
<head>
</script>
<script>
window.onload = function(){
var can1 = document.createElement('canvas');
can1.width = 150;
can1.height = 140;
can1.style.cssText = 'top:2px;left:2px;border:2px solid black;';
var ctx1 = can1.getContext('2d');
var img=new Image();
img.src="images/211.jpg"
ctx1.drawImage(img,0,0);
var can = document.getElementById("c");
var ctx = can.getContext('2d');
ctx.drawImage(can1,0,0);
var canvas = document.getElementById("c");
window.open(canvas.toDataURL());
}
</script>
</head>
<body >
<canvas id="c" style = "position:absolute;top:150px;width:250px;height:350px;left:500px; border:2px solid black;"></canvas>
</body>
</html>
I think the problem was that, when you were trying to drawImage that image into the canvas, image was not ready. so if u do this it works perfectly:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var imageObj = new Image();
imageObj.src = "http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg";
var dynamicCanvas = document.createElement("canvas");
var dynamicContext = dynamicCanvas.getContext("2d");
dynamicCanvas .height="400";
dynamicCanvas.width="578";
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
imageObj.onload = function() {
dynamicContext.drawImage(imageObj, 69, 50);
context=context.drawImage(dynamicCanvas,69,50);
window.open(canvas.toDataURL());
};
};
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
</body>
</html>
and you can adjust the height and width of the dynamic canvas.
if you remove that window.open statement, its perfect.
but there is a problem with canvas.toDataURL()
when you try to do canvas.toDataURL() for a local file, it gives a security error (if you inspect it through google chrome) i.e.
Uncaught Error: SECURITY_ERR: DOM Exception 18
you can know more about this error : here
(see if you are getting this error). anyways, the root cause is sorted out, and there's a new problem now altogether :D..anyways better luck!!
The problem with an incorrect image display using the original code of MJQ is that he doesn't stated the size of the second canvas directly through attributes - only through style. Thus browser created a canvas of default size (300x150 for FF) and then stretched it to 250x350.
So the following modification will solve the image display:
<canvas id="c" width="250" height="350" style = "position:absolute;top:150px;width:250px;height:350px;left:500px; border:2px solid black;"></canvas>
Maybe this will help someone in the future.
what are you taking about? your code is working.
(If am getting your question correctly) I added following lines after
can1.style.cssText='border:2px solid black;';
:
var ctx1 = can1.getContext('2d');
ctx1.rect(50, 50, 500, 500);
ctx1.fillStyle = '#8ED6FF';
ctx1.fill();
and upon execution, i see a beautiful rectangle inside!!
are you using html5 supporting browser??

Can I get image from canvas element and use it in img src tag?

Is there possibility to convert the image present in a canvas element into an image representing by img src?
I need that to crop an image after some transformation and save it. There are a view functions that I found on the internet like: FileReader() or ToBlop(), toDataURL(), getImageData(), but I have no idea how to implement and use them properly in JavaScript.
This is my html:
<img src="http://picture.jpg" id="picture" style="display:none"/>
<tr>
<td>
<canvas id="transform_image"></canvas>
</td>
</tr>
<tr>
<td>
<div id="image_for_crop">image from canvas</div>
</td>
</tr>
In JavaScript it should look something like this:
$(document).ready(function() {
img = document.getElementById('picture');
canvas = document.getElementById('transform_image');
if(!canvas || !canvas.getContext){
canvas.parentNode.removeChild(canvas);
} else {
img.style.position = 'absolute';
}
transformImg(90);
ShowImg(imgFile);
}
function transformImg(degree) {
if (document.getElementById('transform_image')) {
var Context = canvas.getContext('2d');
var cx = 0, cy = 0;
var picture = $('#picture');
var displayedImg = {
width: picture.width(),
height: picture.height()
};
var cw = displayedImg.width, ch = displayedImg.height
Context.rotate(degree * Math.PI / 180);
Context.drawImage(img, cx, cy, cw, ch);
}
}
function showImg(imgFile) {
if (!imgFile.type.match(/image.*/))
return;
var img = document.createElement("img"); // creat img object
img.id = "pic"; //I need set some id
img.src = imgFile; // my picture representing by src
document.getElementById('image_for_crop').appendChild(img); //my image for crop
}
How can I change the canvas element into an img src image in this script? (There may be some bugs in this script.)
canvas.toDataURL() will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Complete example
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
See also:
MDN: canvas.toDataURL() documentation
Do this. Add this to the bottom of your doc just before you close the body tag.
<script>
function canvasToImg() {
var canvas = document.getElementById("yourCanvasID");
var ctx=canvas.getContext("2d");
//draw a red box
ctx.fillStyle="#FF0000";
ctx.fillRect(10,10,30,30);
var url = canvas.toDataURL();
var newImg = document.createElement("img"); // create img tag
newImg.src = url;
document.body.appendChild(newImg); // add to end of your document
}
canvasToImg(); //execute the function
</script>
Of course somewhere in your doc you need the canvas tag that it will grab.
<canvas id="yourCanvasID" />
I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.
the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.
So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/
I hope this helps!
canvas.toDataURL is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
http://jsfiddle.net/gfyWK/67/
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers
Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Categories

Resources