How to display a picture from file input to canvas - javascript

I have following code:
index.html
<!DOCTYPE html>
<html>
<head>
<!-- meta, title, etc -->
</head>
<body>
<input type="file" accept="image/*" id="imgin" /> <br />
<canvas id="canvas"></canvas>
<script type="text/javascript" src="./scripts/main.js"></script>
</body>
</html>
main.js
const imgin = document.getElementById('imgin');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
imgin.addEventListener('change', drawimage);
function drawimage() {
//draw_image
}
Now, I want to draw the Image on canvas when it is choosed.
How should I do so?
All I found were not putting image from <input> tag.

Here is jsfiddle: click.
Used HTML:
<input type="file" id="input"/>
<canvas width="400" height="300" id="canvas"/>
Used JS:
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function() {
ctx.drawImage(img, 0, 0, 400, 300);
}
}

const ctx = canvas.getContext('2d');
imgin.onchange = e => {
const file = imgin.files[0];
if(file) {
const reader = new FileReader();
reader.onload = () => {
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = reader.result;
};
reader.readAsDataURL(file);
}
}
<input type="file" accept="image/*" id="imgin" /> <br />
<canvas id="canvas"></canvas>

Related

how to get entire image inside a canvas element?

I have a canvas element and want to load an entire image inside.
The canvas should be max 50% width.
The loaded images have different widths and heights but in any case I need entire image inside and not just a part of them.
Is it possible?
var URL = window.webkitURL || window.URL;
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles, false);
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 10, 10);
}
img.src = url;
}
#canvas{
max-width:50%;
}
<input type="file" id="input"/>
<canvas id="canvas"/>
drawImage's 4th and 5th parameter is the width and height. The example below will occupy the whole canvas.
var URL = window.webkitURL || window.URL;
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles, false);
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0, ctx.canvas.width, ctx.canvas.height);
}
img.src = url;
}
#canvas {
background-color: salmon;
max-width: 50%;
}
<input type="file" id="input" />
<canvas id="canvas" />
If you want a proportional image, we can use the solution here in calculating
var URL = window.webkitURL || window.URL;
window.onload = function() {
var input = document.getElementById('input');
input.addEventListener('change', handleFiles, false);
}
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
var newDimen = calculateAspectRatioFit(img.width, img.height, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0, newDimen.width, newDimen.height);
}
img.src = url;
}
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {
width: srcWidth * ratio,
height: srcHeight * ratio
};
}
#canvas {
background-color: salmon;
max-width: 50%;
}
<input type="file" id="input" />
<canvas id="canvas" />
If you want a centralized image, you can:
function handleFiles(e) {
var ctx = document.getElementById('canvas').getContext('2d');
var url = URL.createObjectURL(e.target.files[0]);
var img = new Image();
img.onload = function() {
var newDimen = calculateAspectRatioFit( img.width, img.height, ctx.canvas.width, ctx.canvas.height );
var tSpace = ( ctx.canvas.height - newDimen.height ) / 2;
var lSpace = ( ctx.canvas.width - newDimen.width ) / 2;
ctx.drawImage(img, lSpace, tSpace, newDimen.width, newDimen.height);
}
img.src = url;
}

I need to download the image after modification?

I have a function that change image color to black and white and I want to download the image after changed using button
function preview(file) {
if (file) {
var reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function () {
document.getElementById("img").src = reader.result;
document.getElementById("img").style.filter = "grayscale(100%)";
}
}
}
<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br>
<img id="img"/>
There are two things here :
We have to wait for the img.onload function before doing something
We need to copy the filter from the image to the canvas
function downloadImage(imgNode, name = 'fileName', format = 'png') {
const canvas = document.createElement('canvas');
canvas.width = imgNode.width;
canvas.height = imgNode.height;
const context = canvas.getContext('2d');
context.filter = getComputedStyle(imgNode).filter; // Add the image filter to the canvas
imgNode.setAttribute('crossOrigin', 'anonymous');
context.drawImage(imgNode, 0, 0, canvas.width, canvas.height);
const url = canvas.toDataURL(`image/${format}`);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = `${name}.${format}`;
document.body.appendChild(anchor);
anchor.click();
}
function preview(file) {
if (file) {
var reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function () {
var img = new Image();
img.src = reader.result;
img.style.filter = "grayscale(100%)"; // Apply the CSS filter on the image
document.body.appendChild(img); // Display image
img.onload = function() {
downloadImage(img); // Download image
img.onload = null; // Prevent onload function called twice
};
}
}
}
<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br/>
You can do this with Javascript:
First, draw an image in Canvas with CSS and then create anchor tag programmatically and assign click to it
function preview(file) {
if (file) {
var reader = new FileReader()
reader.readAsDataURL(file);
reader.onloadend = function() {
document.getElementById("img").src = reader.result;
var canvas = document.getElementById('cnimage');
var ctx = canvas.getContext('2d');
ctx.filter = "grayscale(100%)"
var img = document.getElementById("img");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
anchor = document.createElement('a');
document.body.appendChild(anchor);
anchor.download = name;
var data = canvas.toDataURL("image/png");
anchor.href = data;
anchor.click();
ctx.clearRect(0, 0, canvas.width,canvas.height);
}
}
}
<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br>
<img id="img"/>
<canvas id="cnimage" height="400px" width="400px"></canvas>

drawImage doesnt work in canvas

I would like to use canvas to compress image file uploaded by user.
my js code is here.
function canvasDraw() {
var file = $("#imageSelect").prop("files")[0];
if (file["type"] != "image/jpeg" && file["type"] != "image/png" && file["type"] != "image/gif") {
$("#imageSelect").val('');
} else {
var fr = new FileReader();
fr.onload = function() {
$("#preview").attr('src', fr.result);
var image = new Image(); 
image.src = $("#preview").attr('src');
var w = 800;
var ratio = w / image.width;
var h = image.height * ratio;
var canvas = $("#canvas");
var ctx = canvas[0].getContext('2d');
$("#canvas").attr("width", w);
$("#canvas").attr("height", h);
ctx.drawImage(image, 0, 0, w, h);
};
fr.readAsDataURL(file);
}
}
<input type="file" name="picture" class='picture' accept="image/*" size="30" id="imageSelect" onChange="canvasDraw();" >
<img src="" id="preview" />
<canvas id="canvas"></canvas>
But in canvas, there is no image shown.
image.width and image.height doesnt work. And ctx.drawImage(image, 0, 0, w, h) doesnt work.
Could you tell me why I have this problem?
image.onload you need to load the image in onload event handler. After load complete it will draw in canvas.
function canvasDraw() {
var file = $("#imageSelect").prop("files")[0];
//画像ファイルかチェック
if (file["type"] != "image/jpeg" && file["type"] != "image/png" && file["type"] != "image/gif") {
alert("画像ファイルを選択してください");
$("#imageSelect").val(''); //選択したファイルをクリア
} else {
var fr = new FileReader();
fr.onload = function() {
//選択した画像を一旦imgタグに表示
$("#preview").attr('src', fr.result);
//imgタグに表示した画像をimageオブジェクトとして取得
var image = new Image(); 
image.src = $("#preview").attr('src');
image.onload = function() {
//縦横比を維持した縮小サイズを取得
var w = 800;
var ratio = w / image.width;
var h = image.height * ratio;
//canvasに描画
var canvas = $("#canvas");
var ctx = canvas[0].getContext('2d');
$("#canvas").attr("width", w);
$("#canvas").attr("height", h);
ctx.drawImage(image, 0, 0, w, h);
}
};
fr.readAsDataURL(file);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="picture" class='picture' accept="image/*" size="30" id="imageSelect" onChange="canvasDraw();" >
<img src="" id="preview" />
<canvas id="canvas"></canvas>

HTML page not displaying the image

I have the following JavaScript file:
var canvas = document.getElementById('Canvas'),
context = canvas.getContext('2d'),
image = new Image();
image.src = 'abc.jpg';
image.onload = function(){
var cols = image.width;
var rows = image.width;
canvas.width = cols;
canvas.height = rows;
context.drawImage(image, 0, 0, image.width, image.height);
};
The HTML file looks as follows:
<html>
<head>
<title>chapter1</title>
<script src="matrix.js">
</script>
</head>
<body>
<canvas id="Canvas"></canvas>
</body>
</html>
But, when I try to view the HTML page, I don't see the image, provided that all the files including the image are in the same directory.
What am I doing wrong?
Thanks.

How can i see text as i type when i draw text on image canvas

I have a canvas setup that allows an image to be uploaded and displayed on the canvas to draw text on the image by grabbing the user input when the sumbit button is clicked. I would like to see the text on image as it is being typed not when i click the submit button.
My index.html.erb
<canvas id="imageCanvas"></canvas>
<input type="file" id="imageLoader" name="imageLoader"/>
<input id="text" type="text" placeholder="your text" style="width: 300px;
height: 28px; z-index: 0;"></input>
<button id="entertext">Submit</button>
My javascript
$(function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
ctx.font = "40pt Calibri";
ctx.fillStyle = 'white';
$('#entertext').click(function(){
ctx.fillText($("#text").val(), 30, 40);
});
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
});
You should put this code:
ctx.fillText($("#text").val(), 30, 40);
into $("#text").on("change", function() { ... here ... }) handler.

Categories

Resources