Download original Canvas even after resizing - javascript

Click here to view image
Step1) I am drawing an image of 1920*1080 to canvas1 with the drawImage(image,0,0);
setp2) Now i am taking another logo image and drawing it to another canvas called canvas2 with the drawImage(logo,0,0);
I used fabricjs to for logo drag able and re sizable functionalities.
Step3) Then i am drawing canvas1 & canvas2 to another canvas called canvas3 and downloading it.
In this case everything is fine except image is displaying large(1920*1080). for user experience I have used image resize method to reduce the image and displayed in 900*500 canvas. But when i am downloding i should get the original canvas of 1920*1080 with logo. But i am getting 900*500 with logo.
Can any one help in this regards will be greatful
The resizing code
Here real width & real Height are width & height of background image
function ImageResize(){
var d_canvas = document.getElementById('canvas');
var context = d_canvas.getContext('2d');
var background = document.getElementById('background');
var wrh = realWidth / realHeight;
newWidth = d_canvas.width;
newHeight = newWidth / wrh;
if (newHeight > d_canvas.height) {
newHeight = d_canvas.height;
newWidth = newHeight * wrh;
}
context.drawImage(background,0,0, newWidth , newHeight);
}

Use the extended form of drawImage to scale and reposition the logo over the original background image:
Create a 3rd html5 canvas sized to 1920x1080 and draw your step1-image to the 3rd canvas.
Recalculate the Logo coordinates & sizes provided by FabricJS from 900x500 to 1920x1080:
// pseudo-code
// Given FabricJS's position & size of the logo on a 950x500 stage
// Calc the logo's relative position & size vs a larger background
logoX *= 1920/900;
logoY *= 1080/500;
logoWidth *= 1920/900;
logoHeight *= 1080/500;
Draw the logo onto the 3rd canvas using the recalculated position & size
thirdContext.drawImage(
logoImage,
0,0,logoImage.width,logoImage.height,
logoX,logoY,logoWidth,logoHeight
);
Export the 3rd canvas

Related

Is it possible to scale a drag image

I am doing drag and drop and want to use a different drag image than the default. But I would also like to scale the size of the drag image depending on the size of the element where the drag starts. I have tried doing the following:
<div id="drag-with-image" draggable="true">drag me</div>
<script>
document.getElementById("drag-with-image").addEventListener("dragstart", function(e) {
var img = document.createElement("img");
img.src = "https://www.w3schools.com/css/paris.jpg";
img.style.width = "60px";
img.style.height = "40px";
e.dataTransfer.setDragImage(img, 0, 0);
}, false);
</script>
But the drag image is always displayed as full size.
Is there any way the drag image size can be scaled dynamically?
Yes, it is possible to scale a custom drag image.
The Problem
If you're using setDragImage with an image element, what will be drawn is the image in its intrinsic size (content size before any modification). This means that setting the image size doesn't help. However, as mentioned in MDN Docs, you can also set a drag image to be something else:
If Element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified).
Furthermore, it also mentions that the "other elements" can be any visible element or even a <canvas>:
However, if a custom image is desired, the DataTransfer.setDragImage() method can be used to set the custom image to be used. The image will typically be an element but it can also be a or any other visible element.
Solution
To draw an image that is smaller than its intrinsic size and setting it to drag image, you can:
Load the image to an image element
Create a canvas to be drawn with the image
When drawing to the canvas, adjust the width and height of the drawn image accordingly
Here's a working example.
document.getElementById('drag-with-image').addEventListener('dragstart', function(e) {
var img = document.createElement('img')
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
// Setting img src
img.src = 'https://www.w3schools.com/css/paris.jpg'
// Drawing to canvas with a smaller size
canvas.width = img.width * 0.1
canvas.height = img.height * 0.1
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
// Setting drag image with drawn canvas image
e.dataTransfer.setDragImage(canvas, 0, 0)
}, false)
<div id="drag-with-image" draggable="true">drag me</div>

How to scale my canvas in reason, with the zoom scale?

I am working on a multiple web game using JavaScript. My canvas is currently set to the width and the height of my screen.
html
<canvas id = "canvas"></canvas>
javascript
var c=document.getElementById("canvas");
var ctx = c.getContext("2d");
//Making canvas scale;
c.width = window.innerWidth;
c.height = window.innerHeight;
function resize(){
//Add some code
}
My problem is, I do not want my players to zoom out, well not by default. It will make the game look bad and give the players an edge over everyone else. So I need to add some code to go into the resize method, that regardless of scale, the canvas will not be zoomed out. If the end result is something blurry at 300%+ that is fine.
IMPORTANT: the resize function cannot remove or reset the canvas back to default.
There are various ways to scale a canvas.
First off, there are 2 main parameters for the canvas size:
-Canvas Pixel Count. Set via canvas.width = 1000
-Canvas Display Pixel Size. Set via canvas.style.width = '1000px'
If you want all players to see a 1000x1000 region but displaying it fullscreen:
canvas.width = 1000;
canvas.height = 1000;
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
There is also another option with canvas.style.transform = 'scale(2,2)'.
This method is the closest thing to the browser zoom done via Ctrl+ or Ctrl-.
The big advantage of transform is that the scaling is applied to all DOM children elements. If your game is using HTML for its interface, then this is the way to go. (By applying the scaling on the div containing the canvas + HTML interface.

How to make overlay scale with image

https://jsfiddle.net/L9xnzqo8/7/
I need the overlay to always be on top of the image no matter what the screen is resized to.
I tries using JS but it doesn't work:
var width = $('.showreel-img').width();
console.log(width);
document.getElementById("video-overlay").style.width = width;

how do make the radius of the circle responsive in canvas element?

I have a canvas element in which I have drawn a circle. How do I give the responsiveness to the canvas element?
If the width of the browser changes I need to change the radius by some amount, if the height of the browser changes I need to change the radius by some amount.
For that how do I need to calculate the changing ratio?
var canvasWidthRatio = currentDivWidth / initialDivWidth;
var canvasHeightRatio = currentHeight / initialDivHeight;
radius = (I need something here)
It appears you're letting the canvas resize based on its div container. That can introduce a problem.
If you resize the canvas's CSS using different percentages for width & height then the canvas content will distort--it will stretch.
To avoid distortion you must resize the canvas width & height proportionally (by the same percentage). The proportionally resized canvas will not necessarily fill the new div size as it did before.
An alternative:
Resize the canvas element itself & use the scaling transformation to redraw your content
This way you won't need to recalculate your circle's radius or position. You can use the exact same drawing commands that were originally used to draw your circle. The canvas's built-in scaling will do all the recalculations for you!
Get a reference to your canvas & your div container and save the original div size
var divcontainer=document.getElementById('mydiv');
var canvas=document.getElementById('mycanvas');
var context=canvas.getContext('2d');
var originalWidth=divcontainer.width;
var originalHeight=divcontainer.height;
Resize the canvas element to the new div size.
var newWidth=divcontainer.width;
var newHeight=divcontainer.height;
// Notes:
// Resizing the canvas element will clear its content
// This alternative allows the canvas to resize disproportionately
canvas.width=newWidth;
canvas.height=newHeight;
Use context scaling to automatically resize the canvas. Any redrawn content will scale automatically using the same original drawing commands.
// calculate the scaling percentage necessary such that
// new content will fit on the canvas
var scaleFactor=Math.min((newWidth/originalWidth),(newHeight/originalHeight));
// scale the canvas
context.scale(scaleFactor);
// now redraw all content (your circle) using their original sizes & coordinates
// unscale the canvas
// (scaling is cumulative, so this cleans up for the next resizing)
context.scale(-scaleFactor);
try this
var radius = 10; // set default radius to start with
var radiusX = Math.min(currentDivWidth , radius); // set horizontal radius to be atleast as wide as width of div
var radiusY = Math.min(currentDivHeight , radius); // set vertical radius to be atleast as high as height of div
radius = Math.min(radiusX, radiusY); // now set the radius of the circle equal to the minimum of the two values so that it is a perfect circle
context.arc(0, 0, radius, 0, 2*Math.PI, false); // use new radius to draw a brand new circle
try using like this:
radius = Math.min(radiusX, radiusY);// here radiusX and radiusY will be currentDivWidth,currentDivHeight resp.
context.arc(0, 0, radius, 0, 2*Math.PI);
see a better description here:http://www.w3schools.com/tags/canvas_arc.asp

Rotate image by 90 degrees on HTML5 Canvas

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

Categories

Resources