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;
Related
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....
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
I'm trying to save my HTML canvas to file which I can successfully do, but it's not saving any objects I've dragged into the canvas.
So, by using the Draggable JQuery I can happily move my object around screen and place it ontop of my canvas. When I save the canvas using the Canvas.ToDataURL() it does not save my dragged objects (and also does something strange to my canvas in the jsFiddle, it appears to change the colour of my canvas?).
To see a "working" example, please visit my jsFiddle http://jsfiddle.net/JVSFS/74/
Please simply drag the green box over the blue box and click the save button. The result will be shown underneath (just an orange box).
HTML
<canvas id="MyCanvas" class="canvas"></canvas>
<div class="popup_click">
<div id="popup_title">Drag</div>
</div>
<asp:HiddenField ID="hideMe" runat="server" />
<asp:Button runat="server" OnClick="ClickMe" Text="Click" OnClientClick="SaveMe()" />
<button onclick="SaveMe()">Try it</button>
<p>Results: </p>
<img id="myImage" />
JavaScript
$(document).ready(function () {
$('.popup_click').show(0).draggable();
});
function SaveMe() {
var canvas = document.getElementById("MyCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "orange";
context.fillRect(0, 0, 100, 100);
var image = canvas.toDataURL("image/png");
document.getElementById("myImage").src = image;
document.getElementById("hideMe").value = image;
}
CSS
.popup_click {
background: #80FF80;
width: 50px; }
.canvas {
width: 100px;
height: 100px;
background-color: #0FC;
}
How can I get the dragged object to save? I assume I have to tell the Canvas that the object is part of it's context but no idea how and my own searches came up with nothing.
From https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
You can't just draw HTML into a canvas. Instead, you need to use an SVG image containing the content you want to render. To draw HTML content, you'd use a element containing the HTML, then draw that SVG image into your canvas.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'>" +
"<foreignObject width='100%' height='100%'>" +
"<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>" +
"<em>I</em> like <span style='color:white; text-shadow:0 0 2px blue;'>cheese</span>" +
"</div>" +
"</foreignObject>" +
"</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
That's because your draggable object isn't in the canves.
They are simple html elements.
It'll save only the objects whose created with canvas methods.
Any way to create html elements on canvas you have to use svg.
Mozilla show nice way to to this but you need to get all the css to inline css before.
mozilla explanation
Anyway with using svg on you canvas you won't be able to use toDataUrl because of security policy.
I am trying to make work a button that would open a new window with the content of my canvas in it (a rendered image of the canvas).
Here's my JS code :
var canvas = document.getElementById("thecanvas");
var dataUrl = canvas.toDataURL();
var context = canvas.getContext("2d");
context.fillStyle = "rgba(0, 0, 255, .5)";
context.fillRect(25, 25, 125, 125);
function clickme() {
window.open(dataUrl, "toDataURL() image", "width=200, height=500");
}
HTML code :
<input type="button" onclick="clickme()" value="OPEN"/>
<canvas id="thecanvas" height="200" width="500" style="border:1px solid black">
But when I click on the "OPEN" button, nothing happens...but I really don't see why. I have looked on alot of sites for tutorials. I even copied and pasted some codes, but still nothing happens. Am I doing something wrong? Thank you!
First off, the order in which you execute your statements matters. You need to call toDataURL after you draw to the canvas, or the dataURL generated with not contain that content.
I'm not sure what your script tags are like, but here's a working example that does the event in a slightly more foolproof way: http://jsfiddle.net/b7G6J/
HTML:
<input id="thebutton" type="button" value="OPEN"/>
<canvas id="thecanvas" height="200" width="500" style="border:1px solid black">
JS:
var canvas = document.getElementById("thecanvas");
var context = canvas.getContext("2d");
// First drawing commands
context.fillStyle = "rgba(0, 0, 255, .5)";
context.fillRect(25, 25, 125, 125);
// Then toDataURL
var dataUrl = canvas.toDataURL();
var button = document.getElementById("thebutton");
button.onclick =function() {
window.open(dataUrl, "toDataURL() image", "width=200, height=500");
}
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....