By creating a canvas
, I want it to always occupy the entire screen. canvas
I am trying to automatically resize the window , but without changing the size of the graphic content it contains.
So that it occupies the entire screen when resizing I am using jQuery:
$(window).resize(function () {
$("#myCanvas").css({ "width": "100%", "height": "100%" });
});
With this shape the content of the canvas is enlarged, and that is not what I am looking for. In the following images I show what I want to avoid. On the one hand, we have any image:
And with the jQuery code that I have written, when resizing the screen, the image contained in the canvas is deformed:
I have added the canvas
to a div
with the intention of giving it context so that the canvas uses the dimension of the div to which it belongs, and modifying with jQuery the dimension not of the canvas
, but of the div
, but in this way the painting area of the canvas
. Do you know of a way to update the dimension of the canvas without altering the already existing graphic content? In the example above I draw a circle, but it could be any graphic element, known or not, so reloading it canvas
with the new size and redrawing the graphic component is not the solution I'm looking for. In the following code I leave the example of using canvas
as a blackboard in which to draw by clicking and moving the mouse, as if it were a "paint".
Here is the code I am using for testing:
$(window).resize(function () {
$("#myCanvas").css({ "width": "100%", "height": "100%" });
});
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.width = parseInt(getComputedStyle(document.getElementById('container')).getPropertyValue('width'));
ctx.height = parseInt(getComputedStyle(document.getElementById('container')).getPropertyValue('height'));
var mouse = { x: 0, y: 0 };
canvas.addEventListener('mousemove', function (e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
canvas.addEventListener('mousedown', function (e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function () {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function () {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
body,
html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
#container {
width: 100%;
height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<canvas id="myCanvas"></canvas>
</div>