Add image to HTML5 Canvas from a file - javascript

In HTML5 Canvas I am trying to add and image.
The line:
imageObj.src = 'file://C:/Users/User/Documents/Image File/image1.jpg';
is not correct.
How do I add a file to HTML5 Canvas Image?
<canvas id="myCanvas" width="1000" height="1000"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var imageObj = new Image();
imageObj.src = 'file://C:/Users/User/Documents/Image File/image1.jpg';
imageObj.onload = function () {
context.drawImage(imageObj, centerX, centerY);
};
</script>

The below example will explain how to use relative paths.
Assume the project structure is like this:
project(think of this as root)/
|->index.html
|->css/
|->main.css
|->images/
|-> cartoon.jpg
|->cat.jpg
|->other_pages/
|->about.html
|->contact.html
Now if we are in index.html page and we should set the image src as:
img = new Image();
cat = new Image();
//accessing cat.jpg
cat.src = "cat.jpg";
//accessing cartoon.jpg
img.src = "images/cartoon.jpg";
Now lets move to about.html page, here we can access the images in the following manner:
img = new Image();
cat = new Image();
//accessing cat.jpg
cat.src = "../cat.jpg";
// accessing cartoon.jpg
img.src = "../images/cartoon.jpg";
// here .. signifies moving one step back
//.. is similar to executing **cd ..** in command line.
For absolute path try this:
Right click on the image and open it in browser, copy the path and set it in imageObj.src (you can use this method if you are working in local environment and want to test it out with few of your local images.)

imageObj.src should be a relative path. For example to an image in the same path, if would be something like imageObj.src = 'image1.jpg';
Path is relative to the html file that is running.

Related

How do I load the image from file chooser and get it to load on the canvas so that i can edit it using Javascript?

I have been using a pixel editor called pixel paint and I wanted to create a button that allows me to load any image onto the canvas. Currently, I have been researching and testing multiple methods online and I am still struggling to get the image loaded in. Here is the code for the script.js method.
function showSelectedFile(){
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var img = new Image();
var file = document.getElementById("inputfile");
var name = file.value.replaceAll("\\","").replace("C:fakepath","").replace(".png","");
document.getElementById("myText").value = name;
window.URL = window.URL || window.webkitURL;
img.onload = function()
{
context.drawImage(img,0,0)
}
img.src = "/Users/angadp/Dropbox/Mac/Downloads/pixel-paint-master/" + name + ".png";
}
Also, in the script.js file I have tried to use
var canvas = document.getElementById("canvas-div")
but it gets the following error
Uncaught TypeError: canvas.getContext is not a function
In the index.html file the code is currently using <div id="canvas-div"></div>. So I am not really sure how to load the image onto the canvas that is using the div tag. Also at the beginning of the html file I am using <input id='inputfile' type='file' accept = ".png" name='inputfile' onChange='showSelectedFile()'> which makes the choose file button.
I also have a picture of pixel paint so that you would know what I am talking about.
Can you please provide me with some help on how to solve all these solutions. Thank you. I have also attached the hyperlink to the original pixel-paint so that you can download and test it.
Pixel Editor Menu for you to download and test
You can load image on change of file. Then createObjectURL (that's data:something;base64). Then load it on an image finally draw it on the <canvas>.
function loadFile(event) {
var canvas = document.querySelector("canvas");
var ctx = canvas.getContext('2d');
var dummy = document.getElementById('dummy');
dummy.src = URL.createObjectURL(event.target.files[0]);
dummy.onload = function() {
ctx.drawImage(dummy, 0, 0, 600, 300);
// Set line width
ctx.lineWidth = 10;
ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(150, 60);
ctx.lineTo(250, 140);
ctx.closePath();
ctx.stroke();
// free memory
URL.revokeObjectURL(dummy.src)
dummy.parentNode.removeChild(dummy)
}
};
canvas {
width: 600px;
height: 300px;
}
<input type="file" accept="image/*" onchange="loadFile(event)">
<canvas></canvas>
<img id="dummy" />

Creating image from two other images using javascript [duplicate]

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?
Update Oct 1, 2008:
Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.
It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.
<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height;
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>
Or, if you want to load the images on the fly:
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();
img1.onload = function() {
canvas.width = img1.width;
canvas.height = img1.height;
img2.src = 'imgfile2.png';
};
img2.onload = function() {
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
};
img1.src = 'imgfile1.png';
</script>
MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:
Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
image1:
image2:
image3:
Result:
Runnable Example:
var canvas = document.getElementById("canvas");
image1 = new MarvinImage();
image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
image2 = new MarvinImage();
image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
image3 = new MarvinImage();
image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
var loaded=0;
function imageLoaded(){
if(++loaded == 3){
var image = new MarvinImage(image1.getWidth(), image1.getHeight());
Marvin.combineByAlpha(image1, image2, image, 0, 0);
Marvin.combineByAlpha(image, image3, image, 190, 120);
image.draw(canvas);
}
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<canvas id="canvas" width="450" height="297"></canvas>
I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.

Export external SVG file painted with Javascript to PNG image

I am using an svg map from an external file. I insert it to my html code using the "object" tag.
<object id="mymap" data="map.svg" width="884" height="760" type="image/svg+xml" ></object>
In javascript I paint paths of the svg map with some given colors. For example:
<script>
var path1 = document.getElementById('mymap').getSVGDocument().getElementById('path1');
path1.style.fill='#f00';
var path2 = document.getElementById('mymap').getSVGDocument().getElementById('path2');
path2.style.fill='#0f0';
</script>
How can I export the resulted coloured map as a PNG image?
--UPDATE-- : The question has been answered, and the LiveExample now includes the solution for future reference. You can view the source and get the solution. The example draws a map and saves drawn map in a canvas that you can then save as file
Example Solution Displaying the canvas
Example Solution Hiding the canvas with direct download to generated image
Solution is the following:
Based on my accepted solution I include the full javascript that manages all steps
Create a canvas
<canvas id="canvas" style="border:1px solid black;" width="884" height="760"></canvas>
Draw into that canvas the image from the painted svg
function drawCanvas(){
// create a canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// define svgdocument and make blob containing its data
var svgDoc = document.getElementById('mymap').getSVGDocument();
var svg = new Blob([svgDoc.lastChild.outerHTML], {type: 'image/svg+xml;charset=utf-8'});
// create a new image
var DOMURL = window.URL || window.webkitURL || window;
var url = DOMURL.createObjectURL(svg);
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0,884,760);
DOMURL.revokeObjectURL(url);
};
img.src = url;
}
Example Solution Displaying the canvas
Example Solution Hiding the canvas with direct download to generated image
What about drawing the svg to the canvas, and then use the .toDataURL to get as PNG image?
--Update--
For a quick test, i run the below in the console from your live demo:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var svgDoc = document.getElementById('mymap').getSVGDocument();
var svg = new Blob([svgDoc.lastChild.outerHTML], {type: 'image/svg+xml;charset=utf-8'});
var img = new Image();
img.onload = function(){ ctx.drawImage(img,0,0); };
img.src = url
you should see the url, which has the image draw, at this time just call the .toDataURL you should get the base64 image data

Trying to display image in an HTML5 canvas

I've tried all code variations that are online. I just want to display an image on a canvas. I've tried code from this site.
window.onLoad=function(){
function draw(){
var ctx = document.getElementById("canvas1").getContext("2d");
var img = new Image();
img.src = 'images/ball.png';
img.onload = function(){
ctx.drawImage(img,0,0);
};
};
};
It's not the file path that's a problem, that has been tested without the images folder. There are no errors in the console. Thanks.
One search in google and there you go with complete jsfiddle example:
// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
// Create an image element
var img = document.createElement('IMG');
// When the image is loaded, draw it
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
// Specify the src to load the image
img.src = "http://i.imgur.com/gwlPu.jpg";
http://jsfiddle.net/jimrhoskins/Sv87G/

Can you combine multiple images into a single one using JavaScript?

I am wondering if there is a way to combine multiple images into a single image using only JavaScript. Is this something that Canvas will be able to do. The effect can be done with positing, but can you combine them into a single image for download?
Update Oct 1, 2008:
Thanks for the advice, I was helping someone work on a js/css only site, with jQuery and they were looking to have some MacOS dock-like image effects with multiple images that overlay each other. The solution we came up with was just absolute positioning, and using the effect on a parent <div> relatively positioned. It would have been much easier to combine the images and create the effect on that single image.
It then got me thinking about online image editors like Picnik and wondering if there could be a browser based image editor with photoshop capabilities written only in javascript. I guess that is not a possibility, maybe in the future?
I know this is an old question and the OP found a workaround solution, but this will work if the images and canvas are already part of the HTML page.
<img id="img1" src="imgfile1.png">
<img id="img2" src="imgfile2.png">
<canvas id="canvas"></canvas>
<script type="text/javascript">
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
canvas.width = img1.width;
canvas.height = img1.height;
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
</script>
Or, if you want to load the images on the fly:
<canvas id="canvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img1 = new Image();
var img2 = new Image();
img1.onload = function() {
canvas.width = img1.width;
canvas.height = img1.height;
img2.src = 'imgfile2.png';
};
img2.onload = function() {
context.globalAlpha = 1.0;
context.drawImage(img1, 0, 0);
context.globalAlpha = 0.5; //Remove if pngs have alpha
context.drawImage(img2, 0, 0);
};
img1.src = 'imgfile1.png';
</script>
MarvinJ provides the method combineByAlpha() in which combines multiple images using its alpha channel. Therefore, you just need to have your images in a format that supports transparency, like PNG, and use that method, as follow:
Marvin.combineByAlpha(image, imageOver, imageOutput, x, y);
image1:
image2:
image3:
Result:
Runnable Example:
var canvas = document.getElementById("canvas");
image1 = new MarvinImage();
image1.load("https://i.imgur.com/ChdMiH7.jpg", imageLoaded);
image2 = new MarvinImage();
image2.load("https://i.imgur.com/h3HBUBt.png", imageLoaded);
image3 = new MarvinImage();
image3.load("https://i.imgur.com/UoISVdT.png", imageLoaded);
var loaded=0;
function imageLoaded(){
if(++loaded == 3){
var image = new MarvinImage(image1.getWidth(), image1.getHeight());
Marvin.combineByAlpha(image1, image2, image, 0, 0);
Marvin.combineByAlpha(image, image3, image, 190, 120);
image.draw(canvas);
}
}
<script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
<canvas id="canvas" width="450" height="297"></canvas>
I don't think you can or would want to do this with client side javascript ("combing them into a single image for download"), because it's running on the client: even if you could combine them into a single image file on the client, at that point you've already downloaded all of the individual images, so the merge is pointless.

Categories