Image rotation using canvas - javascript

I need to rotate an image through canvas and through the cropper.js library I can do the rotation of the image but save the image and condition it with canvas does not save me with the format of the rotation.
In my code what I have is an event that makes me rotating towards 90 or -90 degrees. Then when saving the image I need to be saved with that format.
I need to rotate on the axis of the image so that when the image is saved with rotate canvas it is saved with the correct position. I have seen some ways to do it but it has not worked for me, I do not know that I am losing.
//Events to rotate using cropper Js library
'click #rotateL': function(e, instance){
$('#target').cropper('rotate', -90);
angleInDegrees = angleInDegrees - 90 ;
drawRotated(angleInDegrees);
},
'click #rotateR': function(events, instance){
$('#target').cropper('rotate', 90);
angleInDegrees += 90;
drawRotated(angleInDegrees);
},
function drawRotated(degrees){
var canvas = $("#canvas")[0];
var context = canvas.getContext('2d');
var image = document.createElement("img");
image.src = $('#target').attr("src");
image.onload = function () {
context.drawImage(image,(canvas.width - x1) / 2,
(canvas.height - y1) / 2,x1, y1);
//ctx.drawImage(img, x, y, width, height)
}
context.clearRect(0,0,canvas.width,canvas.height);
context.save();
context.translate(canvas.width/2,canvas.height/2);
context.rotate(degrees*Math.PI/180);
context.drawImage(image, -x1/2,-y1/2);
context.restore();
var dataURL = canvas.toDataURL("image/jpeg");
Session.set("url", dataURL);
}
// event that saves the changes made when you cut the image or rotate.
'click #Save' : function(e) {
$(".loader").fadeIn("slow");
e.preventDefault();
var photoid = $('#photoid').val();
var dataURL = Session.get("url");
var photo = {
srcData : dataURL,
userid : Meteor.userId(),
photo_id : photoid
}
Meteor.call('updatePhoto',photo,function(err) {
if (!err) {
$('#photos').show();
$('#crops').hide();
canvas.height = 0;
canvas.width = 0;
//page relod is better than
//document.getElementById('target').src="";
FlowRouter.go('/search');
FlowRouter.go('/addphoto');
}
});
},

If you are using cropper.js. You can use build-in method getCroppedCanvas to get edited and cropped new canvas back. There is no bother to write on your own.
var canvas = $ ('# target').cropper ('getCroppedCanvas');
console.log (canvas)
var dataURL = canvas.toDataURL ("image / jpeg");

To rotate 90 deg clockwise on a new canvas.
// assuming that image is a loaded image.
const canvas = document.createElement("canvas");
canvas.width = image.height;
canvas.height = image.width;
const ctx = canvas.getContext("2d");
ctx.setTransform(
0,1, // x axis down the screen
-1,0, // y axis across the screen from right to left
image.height, // x origin is on the right side of the canvas
0 // y origin is at the top
);
ctx.drawImage(image,0,0);
To rotate -90Deg onto a new canvas
const canvas = document.createElement("canvas");
canvas.width = image.height;
canvas.height = image.width;
const ctx = canvas.getContext("2d");
ctx.setTransform(
0,-1, // x axis up the screen
1,0, // y axis across the screen from left to right
0, // x origin is on the left side of the canvas
image.width // y origin is at the bottom
);
ctx.drawImage(image,0,0);
The origins are where the top left corner of the image ends up being after the rotation.

Related

Javascript crop and scale image to be 300 pixel

I want to know how we can scale and crop an image in Javascript. I want to scale it down to 300x300px and crop it a little.
Do you have any suggestions ? I have the following code :
function cropImage(imagePath, newX, newY, newWidth, newHeight) {
//create an image object from the path
var img = document.createElement('img');
img.src = "data:image/png;base64,"+imagePath;
//alert(img.width);
//alert(img.height);
//initialize the canvas object
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
//set the canvas size to the new width and height
canvas.width = 300;
canvas.height = 300;
//draw the image
ctx.drawImage(img, newX, 75, 300, 300, 0, 0, 300, 300);
variables.imageCrop = canvas.toDataURL();}
Thank you !
Try it:
And learn more about .drawImage()
function cropImage(imagePath, leftRight, topBottom, newWidth, newHeight) {
const img = document.createElement('img');
img.src = imagePath;
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
img.addEventListener('load', function() {
//Set your canvas size as your choice
//here i just scaled by 10 with original dimension
canvas.width = img.naturalWidth*10;
canvas.height = img.naturalHeight*10;
const cropLeft = leftRight[0];
const cropRight = img.naturalWidth - leftRight[0] - leftRight[1];
const cropTop = topBottom[0];
const cropBottom = img.naturalHeight - topBottom[0] - topBottom[1];
ctx.drawImage(
img,
cropLeft,cropTop,
cropRight, cropBottom,
0,0, //here you can control placement of cropped image from left and top, by default it stays in 0,0 meaning the top left corner of the canvas
newWidth,newHeight //new width and height of cropped image
);
});
}
//Size of this image is 100x100 px
const img = "https://dummyimage.com/100.png/09f/fff";
//here [10,10] meaning crop 10px from left and 10px from right
//here [20,20] meaning crop 20px from top and 20px from bottom
cropImage(img,[10,10],[20,20], 100, 100);

Pattern gets shifted when painting at the bottom edge of the canvas

I would like to paint a repeating grass pattern at the bottom of a canvas. The image does repeat, but it's vertically shifted.
The pattern is based on a 192x50 image:
I've noticed that if I paint from the y-coordinates 50, 100, 150, and so on, the pattern is displayed correctly. It doesn't work at other coordinates.
The resulting canvas has a vertically shifted grass pattern:
I don't know why it gets shifted like that.
Below is my code.
HTML:
<canvas id="myCanvas" style="display: block;">
</canvas>
JavaScript:
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
// Grass Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "img/grass.png";
I do the following in a loop:
if (bgReady) {
ctx.drawImage(bgImage,0, canvas.height -50,192,50);
var ptrn = ctx.createPattern(bgImage, "repeat"); // Create a pattern with this image, and set it to repeat".
ctx.fillStyle = ptrn;
ctx.fillRect(0,canvas.height - bgImage.height,canvas.width, 50); // context.fillRect(x, y, width, height);
}
I tried to put your code in jsFiddle and it seems to work as expected:
var canvas = document.getElementById('myCanvas');
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
// Grass Background Image
var bgImage = new Image();
bgImage.onload = function () {
var ctx = canvas.getContext("2d");
ctx.drawImage(bgImage,0, canvas.height -50,192,50);
var ptrn = ctx.createPattern(bgImage, "repeat"); // Create a pattern with this image, and set it to repeat".
ctx.fillStyle = ptrn;
ctx.fillRect(0,canvas.height - bgImage.height,canvas.width, 50); // context.fillRect(x, y, width, height);
};
bgImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMYAAAAzCAYAAADMxHf3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABbNSURBVHhe7ZzJch3Jd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GAPYUPHKndwQD4A3YLMDKZATTykU7pQXsinaW1SoWxrQpolPg9m8YcExfPIDdELamqyUcGbhTcpyhrys3M7Ayfo5liOMkvPx4Rjhk3BKuIQUe2mja3JI8knAQwp5JqRYWFVY5uUQIZrf9eIhIIIzbEIqIZzNZHumx0jCY4CX/JMjvBp/tfG7HZQMo5ZaavlT+B+r9fQ60AaG/QAAAABJRU5ErkJggg==";
https://jsfiddle.net/or68kcpc/
The error must be somewhere else.
The problem is that the pattern is calculated starting from the top left corner of the canvas. If you paint starting at a canvas y-coordinate that isn't an integer multiple of the image height, the visible portion of the pattern won't start at the top of the image.
To fix this, shift the drawing context down before painting with the pattern, then paint the pattern at a location shifted up, then shift the context back up:
var shiftY = canvas.height % image.height;
context.translate(0, shiftY);
context.fillRect(0, canvas.height - image.height - shiftY,
canvas.width, image.height);
context.translate(0, -shiftY);
Run the snippet below to see a demonstration. The canvas height is 120, which means that we start painting from the y-coordinate 120 - 50 = 70, which is not a multiple of 50.
To correct for this, we shift the context down by 120 % 50 = 20 and then shift the painting location up by 20. Thus, the pattern gets painted on the shifted context at the y-coordinate (70 - 20) = 50, which is a multiple of the image height.
var canvas = document.getElementById('myCanvas'),
context = canvas.getContext('2d');
canvas.height = 120;
canvas.width = 500;
var image = new Image();
image.src = 'http://i.stack.imgur.com/2bfPb.png';
image.onload = function () {
var pattern = context.createPattern(image, "repeat");
context.fillStyle = pattern;
var shiftY = canvas.height % image.height;
context.translate(0, shiftY);
context.fillRect(0, canvas.height - image.height - shiftY,
canvas.width, image.height);
context.translate(0, -shiftY);
};
#myCanvas {
border: 1px solid #666;
}
<canvas id="myCanvas"></canvas>
Let me make one more observation. The loop in your code is inefficient and the bgReady flag is unnecessary because you can run the painting code in the image.onload function, as I have done in my snippet.

canvas hole in html5 with image not working

I am trying to create a hole in canvas; and loading image in canvas after.
I want this canvas to contain a hole at a top layer.
I just read about counter-clockwise canvas rules and then created hole with counter clockwise position as below-
var c = document.getElementById("canvas-front");
var ctx = c.getContext("2d");
var centerX = c.width / 2;
var centerY = c.offsetTop;
var radius = 30;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI,true);//boolean true to counter-clockwise
ctx.fillStyle = 'black';
ctx.fill();
I have canvas before image in it-
After applying image in this canvas-
Canvas-
<canvas id="canvas-front" width="261" height="506"></canvas>
As you can see from both the images, I can't get this hole in canvas work.
How do I create this arc so that image doesn't overlap this.
I get this issue solved-
What I had to do-
On change of file I did empty to canvas and redrew image and then while image is being loaded
the arc is being created to counter-clockwise position-
Drawing the canvas again on image change-
var canvas = document.getElementById("canvas-front");
canvas.width = canvas.width;//blanks the canvas
var c = canvas.getContext("2d");
Creating image and giving it required src from changed input-
var img = new Image();
img.src = e.target.result;
Loading image and creating arc parallely-
img.onload = function () {
c.drawImage(img, 0, 0);
var centerX = canvas.width / 2;
var centerY = canvas.offsetTop;
var radius = 30;
c.beginPath();
c.arc(centerX, centerY, radius, 0, 2 * Math.PI, true);
c.fillStyle = 'black';
c.fill();
}

javascript - Why does this canvas image not rotate correctly?

Why does this canvas image not rotate correctly?
When I click the rotate button the image rotates but gets cropped weirdly. I want the image to stay intact and simply rotate.
Important: I'm not looking to rotate the div, I'm looking to rotate the actual image.
See fiddle:
http://jsfiddle.net/8V4V7/2/
Code:
function rotateBase64Image(base64data, callback) {
console.log("what we get: " + base64data);
var canvas = document.getElementById("dummyCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = base64data;
image.onload = function() {
ctx.translate(image.width, image.height);
ctx.rotate(Math.PI);
ctx.drawImage(image, 0, 0);
callback(canvas.toDataURL());
};
}
EDIT:
I need the image to rotate by 90 degrees on every click.
I tried the following but it doesn't work:
ctx.rotate(Math.PI/2);
This worked for me (I specified the height and width of the canvas inside the onload function):
function rotateBase64Image(base64data, callback) {
console.log("what we get: " + base64data);
var canvas = document.getElementById("dummyCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = base64data;
image.onload = function () {
canvas.height = image.height;
canvas.width = image.width;
ctx.translate(image.width, image.height);
ctx.rotate(Math.PI);
ctx.drawImage(image, 0, 0);
callback(canvas.toDataURL());
};
}
Edit
Updated function to rotate 90 degrees with every click (remove i in i*Math.PI to rotate 90 degrees only once)
var i = 0;
function rotateBase64Image(base64data, callback) {
console.log("what we get: " + base64data);
var canvas = document.getElementById("dummyCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = base64data;
image.onload = function() {
canvas.width = image.height;
canvas.height = image.width;
ctx.translate(canvas.width / 2, canvas.height / 2);
i++;
ctx.rotate(i*Math.PI/2);
ctx.translate(-canvas.width / 2, -canvas.height / 2);
ctx.drawImage(image, 0, 0);
};
}
Updated Fiddle
Just some supporting info for rotations, notably the saving of the context and how to rotate around the center of the image.
var context = canvas.getContext('2d');
//save the context
//pushes a Matrix on the transformation stack
context.save();
context.translate(x, y); //where to put image
context.rotate(angle); //angle in degrees (i think...)
context.scale(scale); //optional scale
//rotate around center of image
context.drawImage(bitmap, -image.width / 2, -image.height / 2);
//or rotate around top left corner of image
context.drawImage(image, 0, 0);
//restore the canvas
//pop a matrix off the transformation stack
context.restore();
References:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations
http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/

Rotate canvas 90 degrees clockwise and update width height

Say we have a canvas:
<canvas id="one" width="100" height="200"></canvas>
And on a button click the canvas gets rotated 90 degrees clockwise (around the center) and the dimensions of the canvas get also updated, so in a sense it looks like this afterwards:
<canvas id="one" width="200" height="100"></canvas>
Note that the id of the canvas is the same.
Imagine simply rotating an image clockwise without it being cropped or being padded.
Any suggestions before I do it the long way of creating a new canvas and rotating and copying pixel by pixel?
UPDATE sample code with suggestion from comments still not working:
function imageRotatecw90(){
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var myImageData = context.getImageData(0,0, cw,ch);
context.save();
context.translate(cw / 2, ch / 2);
context.rotate(Math.PI/2);
context.putImageData(myImageData, 0, 0);
context.restore();
canvas.width=ch;
canvas.height=cw;
}
FiddleJS
Look at this DEMO.
To achieve the results seen in demo, I made use of canvas.toDataURL to cache the canvas into an image, then reset the canvas to their new dimensions, translate and rotate the context properly and finally draw the cached image back to modified canvas.
That way you easily rotate the canvas without need to redraw everything again. But because anti-aliasing methods used by browser, each time this operation is done you'll notice some blurriness in result. If you don't like this behavior the only solution I could figure out is to draw everything again, what is much more difficult to track.
Here follows the code:
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
// Sample graphic
context.beginPath();
context.rect(10, 10, 20, 50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
// create button
var button = document.getElementById("rotate");
button.onclick = function () {
// rotate the canvas 90 degrees each time the button is pressed
rotate();
}
var myImageData, rotating = false;
var rotate = function () {
if (!rotating) {
rotating = true;
// store current data to an image
myImageData = new Image();
myImageData.src = canvas.toDataURL();
myImageData.onload = function () {
// reset the canvas with new dimensions
canvas.width = ch;
canvas.height = cw;
cw = canvas.width;
ch = canvas.height;
context.save();
// translate and rotate
context.translate(cw, ch / cw);
context.rotate(Math.PI / 2);
// draw the previows image, now rotated
context.drawImage(myImageData, 0, 0);
context.restore();
// clear the temporary image
myImageData = null;
rotating = false;
}
}
}
Rotation
Note it is not possible to rotate a single element.
ctx.save();
ctx.rotate(0.17);
// Clear the current drawings.
ctx.fillRect()
// draw your object
ctx.restore();
Width/height adjustment
The only way I ever found to properly deal with display ratios, screen sizes etc:
canvas.width = 20;// DO NOT USE PIXELS
canvas.height = 40; // AGAIN NO PIXELS
Notice I am intentionally not using canvas.style.width or canvas.style.height. Also for an adjustable canvas don't rely on CSS or media queries to do the transformations, they are a headache because of the pixel ratio differences. JavaScript automatically accounts for those.
Update
You also have to update the width and the height before you draw. Not sure what you are trying to achieve, but I guess this isn't a problem:
Demo here
var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
canvas.width = 200;
canvas.height = 400;
// Sample graphic
context.beginPath();
context.rect(10,10,20,50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();
var myImageData = context.getImageData(0, 0, cw, ch);
context.save();
context.translate(cw / 2, ch / 2);
context.putImageData(myImageData, 0, 0);
context.rotate(0.20);
If you want to rotate an image by 90 degrees this might be helpful:
export const rotateBase64Image = async (base64data: string) => {
const image = new Image();
image.src = base64data;
return new Promise<string>((resolve, reject) => {
image.onload = function () {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("cannnot get context '2d'");
canvas.width = image.height;
canvas.height = image.width;
ctx.setTransform(0, 1, -1, 0, canvas.width, 0); // overwrite existing transform
ctx!.drawImage(image, 0, 0);
canvas.toBlob((blob) => {
if (!blob) {
return reject("Canvas is empty");
}
const fileUrl = window.URL.createObjectURL(blob);
resolve(fileUrl);
}, "image/jpeg");
};
});
};
If you don't have image in base64 format you can do it like this:
const handleRotate = async () => {
const res = await fetch(link);
const blob = await res.blob();
const b64: string = await blobToB64(blob);
const rotatedImage = await rotateBase64Image(b64)
setLink(rotatedImage);
}
Here is my blobTob64 function:
export const blobToB64 = async (blob) => {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
};

Categories

Resources