Rotate image by 90 degrees on HTML5 Canvas - javascript

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);
});

Related

how to render smothly P5.js in hdpi screen?

Computer with hdpi screen are more and more common and I own one.
I'm building a webpage with a P5.js canvas inside it filling a div.
I have absolutely no problem till this point, but as I have an hdpi screen the number of pixels to render is tremendous and it's very hard to render smoothly.
what I would like to do: render a low-resolution canvas an stretching it to fill all the space. But I have no ideé how to achieve this or even if it's possible.
function setup() {
var canvasDiv = document.getElementById('myCanvas');
var divWidth = canvasDiv.getBoundingClientRect().width;
var divHeight = canvasDiv.getBoundingClientRect().height;
var sketchCanvas = createCanvas(divWidth,divHeight);
sketchCanvas.parent("myCanvas");
background(0)
}
function windowResized() {
var canvasDiv = document.getElementById('myCanvas');
var divWidth = canvasDiv.getBoundingClientRect().width;
var divHeight = canvasDiv.getBoundingClientRect().height;
resizeCanvas(divWidth, divHeight);
background(0)
}
function draw(){
}
Step one: Create an off-screen buffer using the createGraphics() function. More info can be found in the reference. Give it whatever low-res size you want.
Step two: Draw your scene to that off-screen buffer. Use its width and height to draw stuff to scale.
Step three: Draw the off-screen buffer to the screen, using the image() function, which takes parameters for the size to draw. Use the size of the canvas as the arguments. Again, more info can be found in the reference.
You'll still be drawing the same amount of pixels, but that's how you'd draw to a small buffer and resize it to match the canvas size.
If you're still having trouble, please post a MCVE in a new question post, and we'll go from there. Good luck.

Change an object for a png image on javascript

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

How to rotate part of an image

How can one rotate only a part of an image using javascript/jquery on canvas. I have tried to rotate the image with skew and rotate, but I could not find any answer where we can rotate only some part of an image. All the functions that I have used will rotate an image completely. But, the part rotation of an image keeping the rest of it as it is has not been seen yet.
If I want to rotate only half of an image or something like that, how can I achieve it??
Also, the function shall work when the image is rotated, moved as well as resized dynamically.
Crop the image with drawImage() and draw another instance of that image that you can rotate.
//from http://www.html5canvastutorials.com/tutorials/html5-canvas-image-crop/
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function() {
// draw cropped image
var sourceX = 150;
var sourceY = 0;
var sourceWidth = 75;
var sourceHeight = 150;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = 0;
var destY = 0;
context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
drawRotated(12, imageObj, 225, sourceY, sourceWidth, sourceHeight, 75, destY, destWidth, destHeight);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
//from http://stackoverflow.com/a/17412387/1797161
function drawRotated(degrees, image, sx,sy,sw,sh,dx,dy,dw,dh){
//context.clearRect(0,0,canvas.width,canvas.height);
// save the unrotated context of the canvas so we can restore it later
// the alternative is to untranslate & unrotate after drawing
context.save();
// move to the center of the canvas
context.translate(canvas.width/2,canvas.height/2);
// rotate the canvas to the specified degrees
context.rotate(degrees*Math.PI/180);
context.translate(-canvas.width/2,-canvas.height/2);
// draw the image
// since the context is rotated, the image will be rotated also
context.drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh);
// we’re done with the rotating so restore the unrotated context
context.restore();
}
Here's the fiddle: http://jsfiddle.net/fjhhjh4s/
If i had to make this, i'll use the same image twice: one image full, and a copy with a clipping (css clip property) that i will rotate.
See https://css-tricks.com/clipping-masking-css/
(Sorry to not using comments, i have not the level yet...)
It's possible, but it doesn't seem practical for your project.
You can using a perspective slicing technique:
http://www.subshell.com/en/subshell/blog/image-manipulation-html5-canvas102.html
Ideally you need to define a formula mapping to the original cartesian coordinates from the distorted coordinate system and then iterate over the destination pixel space, using the above mapping to determine the required colour for that pixel.
You would also need to interpolate neighbouring pixels to avoid the output looking "blocky".
This is non-trivial...
You can try OriDomi library if you are looking for crop and animate your image hear is a fiddle.
[Curl image With OriDomi][1]
[1]: https://jsfiddle.net/vipin7/jwqecvt3/17/

JavaScript: Is it possible to cut a shape out of a rectangle to make a transparent hole in it?

I am trying to make a 2d top-down game in Javascript at the moment. I've currently got a day/night system working where a black rectangle gradually becomes more opaque (as the day goes on) before it finally is fully opaque, simulating the peak of the night where the player can not see.
I want to implement an artificial light system, where the player could use a torch that will illuminate a small area in-front of them. However, my problem is that I don't seem to be able to find a way to 'cut out' a shape from my opaque rectangle. By cutting out a shape, it would look like the player has a torch.
Please find an example mock-up image I made below to show what I mean.
http://i.imgur.com/VqnTwoR.png
Obviously the shape shouldn't be as roughly drawn as that :)
Thanks for your time,
Cam
EDIT: The code used to draw the rectangle is as follows:
context.fillStyle = "#000033";
context.globalAlpha = checkLight(gameData.worldData.time);
context.fillRect(0, 0, 512, 480);
//This is where you have to add the cut out triangles for light!
context.stroke();
Instead of drawing a rectangle over the scene to darken it when the "light" is on, instead draw an image with the "lit" area completely transparent and the rest of the "dark" area more opaque.
One way is to use declare a triangular clipping area and draw your revealed scene. The scene would display only inside the defined clipping area.
Example code and a Demo:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var offset = 50;
var img = new Image();
img.onload = function() {
knockoutAndRefill(50,100,300,50,75,350);
};
img.src = 'http://guideimg.alibaba.com/images/trip/1/03/18/7/landscape-arch_68367.jpg';
function knockoutAndRefill(x0,y0,x1,y1,x2,y2){
context.save();
context.fillStyle='black';
context.fillRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.moveTo(x0,y0);
context.lineTo(x1,y1);
context.lineTo(x2,y2);
context.closePath();
context.clip();
context.drawImage(img,0,0);
context.restore();
}
<canvas id=myCanvas width=500 height=400>

Rotating Image on Canvas

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.

Categories

Resources