admin管理员组文章数量:1401681
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.
本文标签: javascriptCan I specify canvas dimensions using vh and vwStack Overflow
版权声明:本文标题:javascript - Can I specify canvas dimensions using vh and vw? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744232351a2596399.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论