My code is:
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.canvas.width = 40vw;
ctx.canvas.height = 40vh;
and it doesn't work. Is it possible to use vw and vh when setting canvas dimensions in JavaScript? If so, how?
My code is:
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.canvas.width = 40vw;
ctx.canvas.height = 40vh;
and it doesn't work. Is it possible to use vw and vh when setting canvas dimensions in JavaScript? If so, how?
Share Improve this question asked Oct 17, 2015 at 21:43 JonahJonah 1,5454 gold badges17 silver badges34 bronze badges 4- 1 Possible duplicate of stackoverflow./questions/1664785/… – andyderuyter Commented Oct 17, 2015 at 21:46
-
You should set the number of pixels with
width
andheight
attributes, whose value is an integer. Then, you can distort it with CSS. – Oriol Commented Oct 17, 2015 at 21:57 - @Oriol That just stretches the image for me. How can I go about setting the width and height attributes as proportions of the view port? – Jonah Commented Oct 17, 2015 at 22:10
-
@Oriol Never mind, just realised I can easily use
document.documentElement.clientWidth
anddocument.documentElement.clientHeight
instead of using vw/vh – Jonah Commented Oct 17, 2015 at 22:12
2 Answers
Reset to default 3I realised I could use document.documentElement.clientWidth
and document.documentElement.clientHeight
to work out the vw and vh respectively.
HTML:
<canvas class="canvas_hangman"></canvas>
JS:
function setUpCanvas() {
canvas = document.getElementsByClassName("canvas_hangman")[0];
ctx = canvas.getContext('2d');
ctx.translate(0.5, 0.5);
// Set display size (vw/vh).
var sizeWidth = 80 * window.innerWidth / 100,
sizeHeight = 100 * window.innerHeight / 100 || 766;
//Setting the canvas site and width to be responsive
canvas.width = sizeWidth;
canvas.height = sizeHeight;
canvas.style.width = sizeWidth;
canvas.style.height = sizeHeight;
}
window.onload = setUpCanvas();
This perfectly sets up your HTML canvas to draw on, in a responsive manner too.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744232351a4564315.html
评论列表(0条)