Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - CSS canvas width and height setting

I am creating canvas element with javascript like

Can=document.createElement("canvas");

Then I want to set the width of this element in centimeters. I am doing

Can.style.width="8cm";
Can.style.height="5cm";

I am setting other css properties like,

Can.style.cssText = 'position:relative; top:24px; left:28px; border-radius:30px; float:left; cursor:pointer; box-shadow: 0px 0px 2px 2px black; background-color:#cdcdcd';

But it is not being set. What's is the problem? How to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to specify the canvas size in pixels. You can then scale the canvas using cm as units.

canvas.width = 500; // px
canvas.height = 300; // px

canvas.style.width = '5cm';
canvas.style.height = '3cm';

The number of pixels in a canvas has to be explicitly/absolutely defined. Centimeters are a relative value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...