So I am trying to build a Meme-Creator. You already can upload the pics as the background-img from the canvas. Now I am trying to do the Meme font but it isnt really working. However it is creating a big gap in the picture. Thanks for your help and attention! :D
var canvas = document.getElementById("meme-canvas");
var ctx = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
function readImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
var img = new Image();
img.addEventListener("load", function() {
ctx.clearRect(0, 0, width, height);
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
});
img.src = e.target.result;
};
FR.readAsDataURL(this.files[0]);
}
}
function Text() {
ctx.clearRect(0, 0, width, height);
var textT = document.getElementById("top-text").value;
var textB = document.getElementById("bottom-text").value;
ctx.font = "60px Impact";
ctx.lineWidth = 3;
ctx.strokeText(textT, 10, 65);
ctx.strokeText(textB, 10, 400);
}
document.getElementById("image-input").addEventListener("change", readImage, false);
<input type="file" id="image-input" accept="image/*">
<input type="text" id="top-text" oninput="Text()">
<input type="text" id="bottom-text" oninput="Text()">
<canvas style="position: absolute; width: 400px; top: 100px; left: 10px;" id="meme-canvas"></canvas>
I've made a few changes to your script. because you need to draw the image several times I've written a function that draws the image. The canvas is cleared every time one of the 2 text input changes it's value, and every time you have to redraw everything.
Also textT and textB can be declared only once. You don't need to declare them in the Text function.
I need to use the font size (60) more than once, so I've made a variable fontSize = 60
Since you don't know the size of your canvas ( depends on the size of the uploaded image ) you need to calculate the position for the bottom text textB = height - fontSize/2 where height is the height of the canvas: height = canvas.height = img.height;
I hope it's useful.
var canvas = document.getElementById("meme-canvas");
var ctx = canvas.getContext("2d");
var width = (canvas.width = 400);
var height = (canvas.height = 400);
var fontSize = 60;
var img = new Image();
var textT = document.getElementById("top-text");
var textB = document.getElementById("bottom-text");
function readImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
img.addEventListener("load", function() {
width = canvas.width = img.width;
height = canvas.height = img.height;
drawImage();
});
img.src = e.target.result;
};
FR.readAsDataURL(this.files[0]);
}
}
function drawImage() {
ctx.drawImage(img, 0, 0);
}
function Text() {
ctx.font = fontSize + "px Impact";
ctx.textAlign = "center";
ctx.lineWidth = 3;
ctx.clearRect(0, 0, width, height);
drawImage();
ctx.strokeText(textT.value, width / 2, 65);
ctx.strokeText(textB.value, width / 2, height - fontSize/2);
}
document
.getElementById("image-input")
.addEventListener("change", readImage, false);
textT.addEventListener("input", Text);
textB.addEventListener("input", Text);
canvas{position: absolute; left: 10px; top:60px;border:1px solid #d9d9d9;}
<input type="file" id="image-input" accept="image/*">
<input type="text" id="top-text" />
<input type="text" id="bottom-text" />
<canvas style="" id="meme-canvas"></canvas>
A few of the issues I encountered:
If you change the size of the canvas you should not use the variables, because those wont be correct, or you will need to keep track of them
If you do clearRect you have to be aware what are you clearing and re-draw it.
The font did not look too clear so I added a white shadow for better contrast
The bottom text needed to be relative to the canvas height
Here is the code:
var canvas = document.getElementById("meme-canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
function readImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
img.addEventListener("load", function() {
canvas.width = img.width;
canvas.height = img.height;
draw();
});
img.src = e.target.result;
};
FR.readAsDataURL(this.files[0]);
}
}
function draw() {
var textT = document.getElementById("top-text").value;
var textB = document.getElementById("bottom-text").value;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "60px Impact";
ctx.shadowColor = "white"
ctx.shadowOffsetX = ctx.shadowOffsetY = 2
ctx.lineWidth = 3;
if (img) ctx.drawImage(img, 0, 0);
ctx.strokeText(textT, 10, 45);
ctx.strokeText(textB, 10, canvas.height -10);
}
document.getElementById("image-input")
.addEventListener("change", readImage, false);
<input type="file" id="image-input" accept="image/*"><br>
<input type="text" id="top-text" placeholder="Top text" oninput="draw()"><br>
<input type="text" id="bottom-text" placeholder="Bottom text" oninput="draw()"><br>
<canvas id="meme-canvas"></canvas>
Related
I got an image, it could be of every size but I need to take the center area of 86x86. Also I've to do that in javascript when a new image is loaded, replacing the old one.
At the end of the code I need to have my 's src updated with the new image.
function loadedImage(elem,gCount){
var crop = { //just messing with numbers
top : 10,
left : 10,
right : 20,
bottom : 20,
};
var file = elem.files[0]; //I take the loaded image
var img = document.getElementsByName('imag')[gCount]; //I take the interessed <img>
var canvas = document.createElement("canvas"); //create canvas
canvas.width = crop.right - crop.left; //set dimensions
canvas.height = crop.bottom - crop.top;
var ctx = canvas.getContext("2d"); // so we can draw
var image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.width = img.width;
image.height = img.height;
image.src = window.URL.createObjectURL(file);
ctx.drawImage(image, -crop.left, -crop.top);
image.src = canvas.toDataURL("image/png");
img.src = image.src;
}
No image is shown
Use a load event listener to wait for your image to load. Once it's ready, you can then start drawing.
To draw the center part of your image, the source x-coordinate should be half the width of your image, minus half the width of the crop. (The source y-coordinate can be calculated in a similar way.)
var input = document.getElementsByName('input')[0];
input.addEventListener('change', function (e) {
var file = e.target.files[0];
drawCroppedImage(file, 86, 86);
});
function drawCroppedImage(file, w, h) {
var canvas = document.getElementById('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
var image = new Image();
image.addEventListener('load', function (e) {
var sx = (image.width / 2) - (w / 2), // Source X
sy = (image.height / 2) - (h / 2), // Source Y
dx = 0, // Destination X
dy = 0; // Destination Y
ctx.drawImage(image, sx, sy, w, h, dx, dy, w, h);
});
image.src = URL.createObjectURL(file);
}
<input type="file" name="input">
<br><br>
<canvas id="canvas" width="86" height="86"></canvas>
I have the following code that allows the user to upload an image which gets put into a canvas, but once it has been drawn I want users to be able to rotate the image with the click of a button, but I don't know how to re-access the image object to be able to rotate the canvas. The code below is what works:
onFilePicked (e) {
const files = e.target.files;
for (let file of files) {
if(file !== undefined) {
let image = {
thumbnail: '/img/spinner.gif'
};
this.images.push(image);
this.loadImage(file, image);
}
}
},
loadImage(file, image) {
const fr = new FileReader();
fr.readAsDataURL(file);
fr.addEventListener('load', () => {
var img = new Image();
img.src = fr.result;
img.onload = () => {
image.thumbnail = this.resizeImage(img, 400, 300);
image.large = this.resizeImage(img, 1280, 960);
}
})
},
resizeImage(origImg, maxWidth, maxHeight) {
let scale = 1;
if (origImg.width > maxWidth) {
scale = maxWidth / origImg.width;
}
if (origImg.height > maxHeight) {
let scale2 = maxHeight / origImg.height;
if (scale2 < scale) scale = scale2;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = origImg.width * scale;
canvas.height= origImg.height * scale;
ctx.drawImage(origImg, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg");
},
And seen below is the function I built out to rotate the image- it works in that if I replace the code inside of the resizeImage function with the code below that the image is drawn in a way that is rotated correctly, but I don't know how to access the origImg object to be able to redraw the canvas in a separate function.
rotateImage(origImg, maxWidth, maxHeight){
let scale = 1;
if (origImg.width > maxWidth) {
scale = maxWidth / origImg.width;
}
if (origImg.height > maxHeight) {
let scale2 = maxHeight / origImg.height;
if (scale2 < scale) scale = scale2;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = origImg.height * scale;
canvas.height= origImg.width * scale;
ctx.translate(canvas.width, 0);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(origImg, 0, 0, canvas.height, canvas.width);
return canvas.toDataURL("image/jpeg");
},
Running this function as-is triggers the following console error:
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
How do I get/reuse the origImg object from the resizeImage function so I can use it in the rotateImage function?
you can try with this code:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(origImg,0,0); // Or at whatever offset you like
};
And apply your code insede onload function of img and finally transform img source to date URL
Try this code, based on one file picker, two buttons. The first one resize image and the second one rotete the image
function resizeImg()
{
var oPicker = document.getElementById('avatar');
var oImage = document.getElementById('imgOut');
var file = oPicker.files[0];
const fr = new FileReader();
fr.readAsDataURL(file);
fr.addEventListener('load', () => {
var img = new Image();
img.src = fr.result;
img.onload = () => {
oImage.thumbnail = this.resizeImage(img, 400, 300);
oImage.src = this.resizeImage(img, 1280, 960);
}
})
}
function rotateImg()
{
var imgOut = document.getElementById('imgOut');
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let scale = 1;
canvas.width = imgOut.height * scale;
canvas.height= imgOut.width * scale;
ctx.translate(canvas.width, 0);
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(imgOut, 0, 0, canvas.height, canvas.width);
imgOut.src = canvas.toDataURL("image/jpeg");
}
function resizeImage(origImg, maxWidth, maxHeight) {
let scale = 1;
if (origImg.width > maxWidth) {
scale = maxWidth / origImg.width;
}
if (origImg.height > maxHeight) {
let scale2 = maxHeight / origImg.height;
if (scale2 < scale) scale = scale2;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = origImg.width * scale;
canvas.height= origImg.height * scale;
ctx.drawImage(origImg, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg");
}
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Image test</h1>
<img src="" id="imgOut" />
<label for="avatar">Choose a profile picture:</label>
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
<input type="button" id="resImg" onclick="resizeImg()" value="Resize" />
<input type="button" id="rotImg" onclick="rotateImg()" value="Rotate" />
</body>
</html>
As you have a part in onFilePicked() where you store something about the images:
let image = {
thumbnail: '/img/spinner.gif'
};
this.images.push(image);
and later update the same objects in loadImage() (well, an event handler in it) as
image.thumbnail = this.resizeImage(img, 400, 300);
image.large = this.resizeImage(img, 1280, 960);
It could be simply extended to
image.original = img;
image.thumbnail = this.resizeImage(img, 400, 300);
image.large = this.resizeImage(img, 1280, 960);
Starting from this point, the objects in your images array would have an original field, storing the original, non-resized variant of the image.
I'm taking image input from user, then resizing and showing it on a canvas. Here is the code-
HTML-
<form class="cmxform">
<input type='file' id="Photo" />
<canvas id="canvas" width="300" height="200"></canvas>
</form>
JavaScript-
$("#Photo").change(function (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, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
}
});
But here I'm loosing the aspect ratio. Is there any way to do it?
UPDATE-
I've got the answer from this sa question -
Here is a snippet to help you for that
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
var fill = true;
if (fill)
{
$('#fill').attr("disabled", true);
}
$("#Photo").change(function (e) {
img.src = URL.createObjectURL(e.target.files[0]);
img.onload = function () {
if (fill)
{
drowImageFill(img);
}
else
{
drowImageCenter(img);
}
}
});
$("#fill").click(function(){
//console.log("fill");
var input = document.getElementById('Photo');
if (input.files[0] !== undefined)
{
img.src = URL.createObjectURL(input.files[0]);
img.onload = function () {
drowImageFill(img);
}
}
$('#fill').attr("disabled", true);
$('#center').attr("disabled", false);
fill = true;
});
$("#center").click(function(){
//console.log("center");
var input = document.getElementById('Photo');
if (input.files[0] !== undefined)
{
img.src = URL.createObjectURL(input.files[0]);
img.onload = function () {
drowImageCenter(img);
}
}
$('#center').attr("disabled", true);
$('#fill').attr("disabled", false);
fill = false;
});
//ratio formula
//http://andrew.hedges.name/experiments/aspect_ratio/
function drowImageFill(img){
ctx.clearRect(0, 0, canvas.width, canvas.height);
//detect closet value to canvas edges
if( img.height / img.width * canvas.width > canvas.height)
{
// fill based on less image section loss if width matched
var width = canvas.width;
var height = img.height / img.width * width;
offset = (height - canvas.height) / 2;
ctx.drawImage(img, 0, -offset, width, height);
}
else
{
// fill based on less image section loss if height matched
var height = canvas.height;
var width = img.width / img.height * height;
offset = (width - canvas.width) / 2;
ctx.drawImage(img, -offset , 0, width, height);
}
}
function drowImageCenter(img)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
if( img.height / img.width * canvas.width < canvas.height)
{
// center based on width
var width = canvas.width;
var height = img.height / img.width * width;
offset = (canvas.height - height) / 2;
ctx.drawImage(img, 0, offset, width, height);
}
else
{
// center based on height
var height = canvas.height;
var width = img.width / img.height * height;
offset = (canvas.width - width) / 2;
ctx.drawImage(img, offset , 0, width, height);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200" style="border:2px solid #000000;"></canvas>
<form class="cmxform">
<input type='file' id="Photo" />
</form>
<button id="fill">Fill</button>
<button id="center">Center</button>
I'm want to make the uploaded image to fill the size of the canvas, by setting the canvas size to the size of the image. The canvas size is set correctly but the image becomes smaller, and doesn't fill the canvas. How can I make the image fill the canvas? here's what I've tried so far.
<canvas id="canvas" style="border: 1px solid #000; width: 400px; height: 300px"></canvas>
<input type="file" name="photo" id="image" accept="image/*">
JS
var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var canvasWidth = 400;
var canvasHeight = 300;
if (image) {
image.addEventListener('change', function () {
var context = canvas.getContext('2d');
if (this.files && this.files[0]) {
var fr = new FileReader();
fr.onload = function (ev) {
var img = new Image();
img.onload = function () {
canvasWidth = img.width;
canvasHeight = img.height;
canvas.style.width = canvasWidth + 'px';
canvas.style.height = canvasHeight + 'px';
context.drawImage(img, 0, 0);
};
img.src = ev.target.result;
};
fr.readAsDataURL(this.files[0]);
}
}, false);
}
var image = document.getElementById('image');
var canvas = document.getElementById('canvas');
var canvasWidth = 400;
var canvasHeight = 300;
if (image) {
image.addEventListener('change', function () {
var context = canvas.getContext('2d');
if (this.files && this.files[0]) {
var fr = new FileReader();
fr.onload = function (ev) {
var img = new Image();
img.onload = function () {
canvasWidth = img.naturalWidth;
canvasHeight = img.naturalHeight;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
context.drawImage(img, 0, 0, canvasWidth, canvasHeight);
};
img.src = ev.target.result;
};
fr.readAsDataURL(this.files[0]);
}
}, false);}
here is you html code
<canvas id="canvas" width="400" height="300" style="border:1px solid red"></canvas>
<input type="file" name="photo" id="image" accept="image/*">
Im using the code below to draw and scale an image inside a canvas. The issue being that the image rendered inside is stretched to fit.
If possible, I would like it to be scaled based on width but to maintain its aspect ratio.
Any ideas?
//IMAGE LOADER
var canvas = document.getElementById('image-canvas');
var canvas2 = document.getElementById('image-canvas2');
ctx = canvas.getContext('2d');
ctx2 = canvas2.getContext('2d');
// Trigger the imageLoader function when a file has been selected
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', imageLoader, false);
function imageLoader() {
var reader = new FileReader();
reader.onload = function(event) {
img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0,canvas.width, canvas.height);
ctx2.drawImage(img,0,0,canvas.width, canvas.height);
}
img.src = reader.result;
}
reader.readAsDataURL(fileInput.files[0]);
}
You can figure out dimensions of the image by adding it to the DOM. Once you know the ratio, you can scale your image to fit within your canvas.
ratio = width / height;
width = height * ratio;
height = width / ratio;
The following should work whether an image is landscape or portrait.
var canvas = document.getElementById('image-canvas');
var canvas2 = document.getElementById('image-canvas2');
var ctx = canvas.getContext('2d');
document.getElementById('fileInput').addEventListener('change', imageLoader, false);
function imageLoader() {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function(){
var ct = document.getElementById('measure');
ct.appendChild(img);
var wrh = img.width / img.height;
var newWidth = canvas.width;
var newHeight = newWidth / wrh;
if (newHeight > canvas.height) {
newHeight = canvas.height;
newWidth = newHeight * wrh;
}
ct.removeChild(img);
ctx.drawImage(img,0,0, newWidth , newHeight);
}
img.src = reader.result;
}
reader.readAsDataURL(fileInput.files[0]);
}
/* Add image to the DOM here so user can't see it */
#measure { position: absolute; left: -10000px; top: -100000px;}
canvas { border: 1px solid red; }
<canvas id="image-canvas" width="300" height="300"></canvas>
<input type="file" id="fileInput" />
<div id="measure"></div>
You can play with it here