Resizing a canvas element via dragging the edges - javascript

I'm trying to make it so users of my site can resize their canvas by simply dragging the sides of it. I'm using Fabric.js which allows me to resize elements from within the canvas but I need to resize the actual canvas itself. I'm fine with using any new libraries you recommend.
This image should help you understand a bit more of what I want.
As a side note, the Fabric.js team have an interactive toolbox here for you to experiment if you need it.

Put your fabric.js canvas in a wrapper div.
Make the wrapper resizable. Here I'm using CSS resize. It only adds a bottom-left corner as a resize control but it's good enough for the sake of the demo. To have all the edges as controls you can try something like this.
Detect the wrapper's size change. Ideally, you would use something like ResizeObserver. However, since browser support is still about 80% at the time of posting this, you might feel the need to use a polyfill or write something specific to your case. A simple setInterval with size check might prove to be sufficient.
When the wrapper's size changes, set new fabric.js canvas dimensions via setWidth() and setHeight().
const canvas = new fabric.Canvas('c')
canvas.add(new fabric.Rect({
width: 100,
height: 100,
fill: 'red',
left: 100,
top: 50,
}))
const canvasWrapper = document.getElementById('wrapper')
// initial dimensions
canvasWrapper.style.width = '300px'
canvasWrapper.style.height = '150px'
let width
let height
setInterval(() => {
const newWidth = canvasWrapper.clientWidth
const newHeight = canvasWrapper.clientHeight
if (newWidth !== width || newHeight !== height) {
width = newWidth
height = newHeight
canvas.setWidth(newWidth)
canvas.setHeight(newHeight)
}
}, 100)
#wrapper {
border: solid 1px black;
resize: both;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<div id="wrapper">
<canvas id="c"></canvas>
</div>

This isn't something that's going to be easy, but it's definitely possible. First, you may wonder about the native browser element resize CSS property and ResizeObserver, however those have poor support right now. Your best option is to:
Create a canvas element
Detect mousemoves on the canvas:
If the mousemove happens around the edge of the canvas, set the cursor to be the resize icon in the proper direction
If the mouse is currently down, resize the canvas based on the mouse's position.
Remember that every time you resize a canvas, the current image on the canvas is wiped.

Related

Canvas mouse events delayed when using resized via CSS

I am playing around with a project to learn more about node.js & html canvases.
In my project I have a canvas that I want to keep a fixed bitmap size, but fill its containing div while maintaining its aspect ratio.
I have applied a size of 500x500 to my canvas element, and then applied the following style in CSS.
canvas {
display: block;
width:100%;
height:100%;
object-fit: contain;
background-color: lightgrey;
}
Inside the javascript initially fill the canvas white so I get something like the below, so far so good.
I hook into the mouse events and use them to draw lines. I use the below function to correctly scale events to the canvas.
function getMousePos(evt) {
var rect = canvas.getBoundingClientRect(); // abs. size of element
var raw_x = evt.clientX||evt.touches[0].clientX;
var raw_y = evt.clientY||evt.touches[0].clientY;
var min_dimension = Math.min(rect.width,rect.height);
var x_offset = 0.5*(rect.width-min_dimension);
var y_offset = 0.5*(rect.height-min_dimension);
return {
x: ((raw_x - rect.left - x_offset) / min_dimension) * canvas.width,
y: ((raw_y - rect.top - y_offset) / min_dimension) * canvas.height
}
}
This works, however when drawing on the canvas when the mouse moves over a band on the right side of the image it doesn't update until the mouse leaves the band. The band is the same size as the space on the left of the canvas so I think its related but I don't know how to investigate. I have no Issues if I resize the window till there is no space on either side of the canvas bitmap (and performance is considerably faster). The below gif should make things more clear.
Does anyone have a suggestion on what could be causing this, or a better way for me to achieve the same effect.
Note: I am running chrome version 80.0.3987.149
For anyone else that comes across this, I couldn't find a good solution, beyond using JavaScript to resize the element when the window resize event occurs.

Resizing canvas size gives advantage to larger screens. Not sure how to keep the functionality while making it fair

So I am trying to learn javascript by making a game where you click on a canvas to move a circle and you have to dodge multiple other circles coming in your direction. I am close to the final result but I just realized that the larger your screen is, the easier it is for you to play.
The reason is that the enemies spawn at the edges of the canvas, so if the canvas is bigger, you have more time to react to them since their speed doesn't change. The game is supposedly refreshing around 60fps and each time it resizes the canvas depending on if you change your window size. The only thing I can think of is increasing the speed of enemies with the size increase but I don't know if there's any other way to go about this. Maybe I could increase the size of the of the player and the enemies to accommodate the change in window size but I don't know which is better or how to make sure I am consistent with the ratio increase.
Any suggestions would be much appreciated. Thanks for your time
Here's my full code: https://jsfiddle.net/r2f6eb89/2/
It doesn't actually run on this site so it's just a reference for my logic.
Here are the resizing functions:
/*
function setCanvasSize() {
//c.width = window.innerWidth-100;
//c.height = window.innerHeight-100;
if (window.innerWidth < window.innerHeight) {
c.width = window.innerWidth - 150;
c.height = window.innerWidth - 150;
} else {
c.width = window.innerHeight - 150;
c.height = window.innerHeight - 150;
}
}
*/
function setCanvasSize() {
c.width = 600;
c.height = 600;
}
There's actually two kinds of "width" and "height" property. One is the width and height you can actually see in your website, that is, the one you can change by the property on your html file element. The other one is the width and height you set in the javascript file, for setting the coordinate you use to print image or draw in the canvas.
Example for first type of the width/height property:
<canvas id="my_canvas" width="500" height="200"></canvas>
Example for second type of the width/height property:
var canvas = document.getElementById("my_canvas");
canvas.width=500;
canvas.height=200;
It seems like you are changing the second type of the width/height property each refresh. If that's not what you want, try modifying the first type of width/height. It seems like a simpler solution to your question. To modify the first type of property, the CSS property in javascript, here's the code:
canvas.style.width="500px";
canvas.style.height="200px";
Hope that helps :)

Update HTML canvas width and height attributes automatically

I want to use HTML5 canvas with flexbox. I need to set canvas.width and canvas.height automatically when user resizes window. I have tried to use jQuery for it:
$(".cnvs").attr("width", $(".cnvs").width());
$(".cnvs").attr("height", $(".cnvs").height());
but it keeps increasing actual width of canvas so it almost fills entire screen. I have put it on jsfiddle - try to resize output window with separator.
Is there any reasonable way how to do it? Thanks.
Edit: Just to be clear: I don't want to fill entire screen with that canvas. I want UI where I have:
<div class="container">
<div class="control"></div>
<canvas></canvas>
<div class="control"></div>
</div>
then use flexbox to put those three elements beside eachother, while canvas will be twice as wide as the other. This works without problem, but canvas.width and canvas.height doesn't get updated, so whenever I render something onto that canvas, it is rendered as if that canvas was 320x140 px.
Edit 2: I am sorry, but (perhaps because of my poor English) I am not clear enough. I will try to explain it once again:
Actual width of canvas element is correct (even without using any JavaScript code) only by using flexbox. My problem is that although width is correct (and $(".cnvs").width() returns correct value of width), it doesn't have any "width" attribute, it is still:
<canvas>
</canvas>
and I need to provide width argument by myself (because it renders badly when it's not set). When I try to use my code or proposed:
...
var rect = canvas.parentNode.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
...
it behaves weirdly, canvas's width keeps increasing with every resize, but too much (it erases both control divs almost immediately).
Update 2
If I understand the question correct: the canvas has a flex CSS set (not shown in the question right now). It defines the canvas to be 2x the size of the other two elements, but since the canvas is resized and not its bitmap, the drawings are stretches as well and you want the bitmap to adopt dynamically.
If so, do this change to the code -
This update will leave the CSS rules of the canvas element alone and let flexbox handle it. It will read the actual pixel size of the element and then apply it to the bitmap so that data isn't stretched:
$(window).on("resize", function() {
var cnvs = $(".cnvs")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself
cnvs.width = rect.width;
cnvs.height = rect.height;
// ... redraw content here ...
}
Additionally, since resizing the window can produce a lot of events, you may want to consider "debouncing" so that you only deal with the more recent resize:
var timerID;
$(window).on("resize", function() {
clearTimeout(timerID);
timerID = setTimeout(function() {
var cnvs = $(".cnvs")[0]; // cache canvas element
var rect = cnvs.getBoundingClientRect(); // actual size of canvas el. itself
cnvs.width = rect.width;
cnvs.height = rect.height;
// ... redraw content here ...
}, 180); // adjust at will
}
This will delay the resizing/redrawing until 180ms has passed.
You don't even have to load jQuery, it is simple:
var canvas = document.querySelector("canvas");
window.addEventListener("resize", function(){
canvas.setAttribute("width", window.innerWidth);
canvas.setAttribute("height", window.innerHeight)
})
You have to add a listener to the resize event on the window object.
If your looking for a jquery solution.
$( window ).resize(function() {
$(".cnvs").attr("width", $(window).width());
$(".cnvs").attr("height", $(window).height());
});
This should work just fine.

Canvas line width changes as browser window size changes, any idea to work around?

I have a canvas inside a div and it fills the whole div. I draw a line on canvas but when I resize browser window, width of the line on the canvas changes, as I increase browser window size its thickness increases and adds some blur to the line.
I figured out that problem occurs here; I dont use a fixed size for canvas instead I use %100 for the width and height.
#myCanvas{
margin:0;
padding: 0;
border:0;
width: 100%;
height: 100%;
background-color: white;
}
When I used fixed size in pixeel for width and height, it's ok. But I want my canvas to resize without disturbing the drawing inside.
You can play around here: http://codepen.io/ertugrulmurat/pen/nxhof
Just try to change the heigth of browser window.
Any idea would be appreciated.
This is unfortunately quite involved to fix. Essentially you need to:
Add an event listener to the window for the resize event and
change the width/height attributes on the canvas tag (not the css, that stays at 100%) every time the window resizes
You will also need to redraw the line every time the resize happens.
Remember the width/height attributes are unitless so make sure you set it to something like width="100" and not width="100px"
Here is the relevant section of your code with the corrections in place:
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.canvas.width = ctx.canvas.clientWidth;
ctx.canvas.height = ctx.canvas.clientHeight;
var draw = function(){
ctx.lineWidth = 0.5;
ctx.shadowBlur = 0;
ctx.strokeStyle="#FF0000";
ctx.beginPath();
ctx.lineWidth=0.5;
ctx.lineCap="round";
ctx.moveTo(20,20);
ctx.lineTo(200,20);
ctx.stroke();
ctx.closePath();
}
window.addEventListener('resize', function(){
ctx.canvas.width = ctx.canvas.clientWidth;
ctx.canvas.height = ctx.canvas.clientHeight;
draw();
});
draw();
}
I've taken a look around and it seems that the canvas element doesn't deal well with CSS, and it's best to define the width and height as part of the tag, such as
<canvas width="200" height="100"></canvas>
Of course the only problem is that those values are only in px. My work around would be to use javascript to therefore collect the parent size and enter the new value on the resize event. I have wrote all this out in a jsfiddle for you and it works brilliantly if you resize.
Note that I call the redraw function every time it is resized. If you fail to do this, it goes blank until the next click.
http://jsfiddle.net/N23w2/1/

Which jQuery method of creating a canvas of a certain size has the best performance?

What I'd like to do is create a 15 by 15 pixel sized canvas with jQuery and I am looking for an elegant way to do it.
I currently create a canvas with jQuery like this:
var canvasNode = $('<canvas />', {
style:'display:block',
width:15,
});
// canvasNode[0].width=15;
canvasNode[0].height=15;
An oddity is that the width:15 in that has no effect while the currently commented out line below does what I'd like to do. I also tried style:'display:block;width:15px;' but while that displays the canvas at 15px width the canvas itself stays at its large default size so its just being scaled so that's not what I seek.
In case you are really worried about performance, this is the fastest way (untested, but I'm sure it is):
var canvas = document.createElement("canvas");
canvas.width = 15;
canvas.height = 15;
That is, no jQuery at all.
Note that sending in an object with a width property will set the css width to 15px (basically just scaling the canvas), the canvas will still be created with the default number of pixels in width if no width attribute is specified, which is usually 300 pixels.
Just set the width and height attributes:
$('<canvas />', {
style:'display:block'
}).attr('width', 15).attr('height', 15);

Categories

Resources