I am attempting to use javascript to take a picture with my iphone and draw the image to the canvas. I use
<input type="file" capture="camera" accept="image/*" id="takePictureField">
mobilePictureGet);
to use the camera. Once I choose a picture
document.getElementById("takePictureField").addEventListener('change', function(e) {
if(e.target.files.length == 1 && e.target.files[0].type.indexOf("image/") == 0) {
img.src = URL.createObjectURL(e.target.files[0]);
}
}
this fires, and the image appears how I want it in the tag. (so far so good), However, I draw it to the canvas when img tag has loaded:
img.onload = function() {
ctx.drawImage(img, 0, 0, img.width,img.height);
}
and it appears rotated -90 degrees. I have tried
var x = width / 2;
var y = height / 2;
var angleInRadians = Math.PI / 2;
ctx.translate(x, y);
ctx.rotate(angleInRadians);
ctx.drawImage(img, -width / 2, -height / 2, img.width, img.height);
ctx.rotate(-angleInRadians);
ctx.translate(-x, -y);
but I can't get it to fit.
Does anyone know why the canvas would draw the image rotated? Any help to get the picture drawn correctly on the canvas is much appreciated!!
Thanks!
It probably depends on how you hold your phone. That (orientation) information is stored in the exif data of the image and you have to rotate it accordingly.
One library that can help you with this is JavaScript Load Image
I've never tried to take a picture with javascript, but I do some ios mobile development.
The reason the picture comes out sideways at all, is because apple has deemed that holding your phone with the home button facing right is the only acceptable way to take a picture. This is also known as it's 'up' state.
More information on why your iPhone takes pictures sideways can be found here: http://rotatemailer.com/sideways-pictures.html
In ios it's very easy to rotate it, so in javascript i'm not too sure how to properly do that.
Related
I adapted an open source game to fit for my fantasy book series, Eloik.
This game
I'd like to replace the blue arc for a png image (about same size).
I know I have to draw an image but how to??
Here's the portion of the code :`
// Shield - Boomlight
context.beginPath();
context.strokeStyle = '#0066cc';
context.lineWidth = 10;
context.arc( player.position.x, player.position.y, player.radius,
player.angle + 1.6, player.angle - 1.6, true );
context.stroke();`
I tried that following code but... The png image doesn't appears at the right spot and it's not interactive with the game as the arc...`
<html>
<body>
<img id="boom" width="176" height="134" src="http://eloik.com/wp/wp-
content/uploads/2017/05/BOOMLIGHT-jeu-bd.png" alt="">
*In the Javascript :
<script>
window.onload = function() {
var image = new Image();
image.src="http://eloik.com/wp/wp-content/uploads/2017/05/BOOMLIGHT-jeu-
bd.png";
context.beginPath();
context.drawImage(image, 10, 10);
}
</script>
</body>
</html> `
So now, what's wrong ?
Thanks ! :)
First, in order to use drawImage, we need to load it. You can do it like this:
/* core.js: line 57 */
// Create a handle for the image
var shieldImage;
/* core.js: line 133 */
// Create a new image
shieldImage = new Image();
// When it's loaded, execute animate
shieldImage.onload = animate;
// Set the src
shieldImage.src = "http://eloik.com/wp/wp-content/uploads/2017/05/BOOMLIGHT-jeu-bd.png";
This way, the animate function will only be called once the image has loaded. Then, in order to position your image and rotate it, you can do this:
/* core.js: line 420 */
// Set the origin of the canvas on the player position
context.translate(player.position.x, player.position.y);
// Rotate the canvas
context.rotate(player.angle + Math.PI + .2);
// Draw the shield
context.drawImage(shieldImage, -player.radius, -player.radius, player.radius*1.5, player.radius*2.3);
// Rotate the canvas back
context.rotate(-player.angle - Math.PI - .2);
// Reset the initial origin of the canvas
context.translate(-player.position.x, -player.position.y);
Since we cannot rotate the image itself, we use this trick, which consists in rotating the canvas, drawing, and reverting the rotation of the canvas. We also translate it in order to have the rotation axis on the player position.
You'll also notice I added some numbers in there. That's because your shield image is not a perfect circle. I distorted it so that it does not look weird with the current collision system (which is based on a circle). If you want to keep the oval shape of the image, you'll need to make more serious changes to the rest of the code so that collisions apply to that shape.
And that's it, your blue arc is replaced with your PNG image (Updated JS here)
PS: You have a cool last name ! - same as mine
In my web app I am allowing users to choose images. If the height of the image is greater than the width then I rotate the image by 270 degrees.
I am confuse about what should be the ideal size for the rotated image as I would be saving that rotated image later on.
For example if a user upload a image with low resolution what should be the size there and what if the user uploads an image with a high revolution what would be the size than?
I don't want the pixels to be distorted. Any good library to rotate image on the client side? Or any algorithm which can help me?
You could try the naive canvas approach like this:
Basically you'll be drawing the image on a canvas, rotated, then saving the canvas to a dataUrl
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 (in the canvas)
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();
//now save the canvas to a data url for download or to display in an image object / tag
var data = canvas.toDataUrl();
References:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations
https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement
http://html5.litten.com/understanding-save-and-restore-for-the-canvas-context/
you can use Blob object approach. Convert the image to blob objects and you can play with it. I cant help with code coz am not much aware of blobs. Please do more research on blobs and you can achieve what you want to do using Blobs.
I am having trouble rotating an image using an HTML5 canvas. I suppose that I just have the math wrong, and would appreciate any help in getting this right.
On a mobile device I am capturing a user signature on a 150px by 558px canvas. I am than attempting to create a 558px by 150px image that is just the captured signature rotated 90 degrees. Below is a snippet of the code I've currently come up with. As you can likely surmise, I do not have a good grip on the math going into this. I believe I have the procedure correct, just not the numbers.
What I'm trying to do is:
1) set the center of the canvas to the middle, offsetting by the height and width of my image
2) rotate the canvas by 90 degrees
3) draw the image
4) translate the canvas back.
EDIT: Here's a JSFiddle: http://jsfiddle.net/x9FyK/
var $signature = $("#signature");
var signatureData = $signature.jSignature("getData");
console.log(signatureData);
var img= new Image();
img.onload = function() {
var rotationCanvas = document.createElement('canvas');
rotationCanvas.width = img.height;
rotationCanvas.height = img.width;
var context = rotationCanvas.getContext("2d");
context.translate((rotationCanvas.width/2) - (img.width/2), -(rotationCanvas.height/2) - img.height/4);
context.rotate(Math.PI/2);
context.drawImage(img,0,0);
context.translate(-((rotationCanvas.width/2) - (img.width/2)), -(-(rotationCanvas.height/2) - img.height/4));
var rotatedData = rotationCanvas.toDataURL();
...Handling rotated data here
};
img.src = signatureData;
If I can provide any more information, please let me know.
Thanks in advance for your help,
There are several ways of resetting a transformed (translated+rotated) canvas back to its original state.
Low-Pointer's answer is using context.save to save the context in is original un-transformed state and using context.restore to restore the context to its original state after the drawing is done.
The other way it to undo your transforms in the reverse order that they were performed.
Also, note that context.translate will actually move the canvas origin to the center of the canvas. Since images are drawn from their top-left (not their center), you must offset drawImage by half the image width and height if you want the image centered in the canvas.
Here's and example: http://jsfiddle.net/m1erickson/EQx8V/
// translate to center-canvas
// the origin [0,0] is now center-canvas
ctx.translate(canvas.width/2,canvas.height/2);
// roate the canvas by +90% (==Math.PI/2)
ctx.rotate(Math.PI/2);
// draw the signature
// since images draw from top-left offset the draw by 1/2 width & height
ctx.drawImage(img,-img.width/2,-img.height/2);
// un-rotate the canvas by -90% (== -Math.PI/2)
ctx.rotate(-Math.PI/2);
// un-translate the canvas back to origin==top-left canvas
ctx.translate(-canvas.width/2,-canvas.height/2);
// testing...just draw a rect top-left
ctx.fillRect(0,0,25,10);
this will surely help you >>HTML5 Canvas Rotate Image :)
use some SEPARATE js function for drawing your canvas :
function drawRotated(degrees){
contex_var.clearRect(0,0,canvas.width,canvas.height);
contex_var.save();
contex_var(canvas.width/2,canvas.height/2);
contex_var.rotate(degrees*Math.PI/180);
contex_var.drawImage(image,-image.width/2,-image.width/2);
contex_var.restore();
}
Suppy some angle to any buttonclick function:
$("#clockwise").click(function(){
angleInDegrees+=30;
drawRotated(angleInDegrees);
});
I'm seeking to create a custom fade in with jQuery or JS. I'd like the fade to be exaggerated and go from very blurry, to pixelated, to then the clear crisp image. On page load, one time.
This is for one image. Yes, tradditionaly done via making an animated gif I suppose. But can I write the effect with jQuery?
On page load. Grabbing the image #div >
Image loads blurry > then pixelates in > and then the clear original HQ image resolves.
To pixelate an image you can use canvas directly in a simple way like this (here assuming image has already been loaded):
/// get a block size (see demo for this approach)
size = blocks.value / 100,
w = canvas.width * size,
h = canvas.height * size;
/// draw the original image at a fraction of the final size
ctx.drawImage(img, 0, 0, w, h);
/// turn off image aliasing (see comment below)
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false; /// future
/// enlarge the minimized image to full size
ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);
Here is an online demo.
You can use the slider at the bottom to see various sizes and the speed which would be needed for your transition (use Chrome to see live update when moving the slider) or simply hit the animate button.
As we turn off interpolation (image smoothing) the new enlarged image will appear blocky. This method is also faster than most other approached mainly due to image smoothing can now be turned off in the major browsers.
See this answer for a more complete instruction on how to turn smoothing off in most browsers:
Images in web browser are slightly blurred. How to disable it?
The last drawImage will use a clipped part of the source (here: canvas itself). See here for more details on how to use this method.
As for blur effect I would recommend you to pre-blur the image as this process has a large overhead and the pause will be noticeable on most common computers.
In case you still want to blur the image "live" you can use this stack-blur:
http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
You could use Close Pixelate by David DeSandro. The Pixelator is a good example of it in action.
My client is experiencing a bizarre bug in Firefox 12 on Windows: a blue tinted box is appearing around the drawn image in the canvas.
The canvas is inside an iframe inside a fancybox div. You may be able to see this in action by clicking the image thumbnail under the main image on this site:
http://mattmatthias.com/a/index.php?route=product/product&path=20&product_id=80
At first, I thought it was a selection issue, although the fact that the drawn image itself rather than the whole canvas seems to refute that. I've tried again and again to blur the canvas, the container div, the iframe... everything, to no avail.
What's worse, I can't reproduce this bug. Everything functions normally in Safari, Firefox, Chrome, and Opera on my mac.
This is probably the offending code, as it's the only part of the code that draws anything:
if(imageWidth == 0) return;
context.clearRect(0, 0, canvasWidth, canvasHeight);
var x_adjust = -x-(ratio*canvasWidth -canvasWidth )/2;
var y_adjust = -y-(ratio*canvasHeight -canvasHeight )/2;
var width = scaledWidth*ratio;
var height = scaledHeight*ratio;
if(x_adjust < canvasWidth - width)
x_adjust = canvasWidth - width;
if(x_adjust > 0)
x_adjust = 0;
if(y_adjust < canvasHeight - height)
y_adjust = canvasHeight - height;
if(y_adjust > 0)
y_adjust = 0;
if(width < canvasWidth) {
x_adjust += (canvasWidth - width) / 2;
}
if(height < canvasHeight) {
y_adjust += (canvasHeight - height) / 2;
}
context.drawImage(image, 0, 0,
imageWidth, imageHeight,
x_adjust, y_adjust,
width, height);
Any ideas? As I get more details, I will post them here.
This isn't related to the canvas; just opening the image in Firefox shows the same thing. So it's a problem with reading/rendering the image.
This Mozilla support issue sounds like precisely what's happening here, and it's related to a color management issue.
And indeed, removing the color profile from the image file makes the image look correct.
Depending on the particular case, instead of just stripping the profile you may want to do some conversion instead; whether that's necessary depends on the particular image, profile, and on how big the probability is that color management even remotely has a chance of producing something meaningful on your visitors' monitors (unless you cater to graphic designers: probably not very big).