我想使用JavaScript在响应式画布上绘制圆圈。我正在获取画布的宽度和高度,但是由于div标签的宽度和高度%,我能够正确绘制圆形。div标签的宽度和高度以%为单位,因为我想在单个页面上显示5个画布。是否有其他方法可以在单个页面上放置5个画布,并使用画布的高度和宽度在每个画布中绘制一个圆?还有一件事,我不需要绝对位置,因为根据浏览器宽度,我想更改画布位置
图片:192.168.10.29/1.png
的CSS
.all
{
width:30%;
height:45%;
float:left;
}
canvas
{
width:100%;
height:100%;
}
的HTML
<div id='container'>
<div class='all'>
<canvas id='clock1' style="border:solid">
</div>
<div class='all'>
<canvas id='clock2' style="border:solid">
</div>
<div class='all'>
<canvas id='clock3' style="border:solid">
</div>
<div class='all'>
<canvas id='clock4' style="border:solid">
</div>
<div class='all'>
<canvas id='clock5' style="border:solid">
</div>
</div>
Java脚本
function draw(canvasarray)
{
var clock = document.getElementById(canvasarray);
var style = getComputedStyle(document.getElementById(canvasarray));
var height = parseInt(style.getPropertyValue("height"),10);
var width = parseInt(style.getPropertyValue("width"),10);
var radius = 0;
console.log('Width : ' + width + ' Height : ' + height);
if(width < height)
{
radius = width/2;
}
else
{
radius = height/2;
}
console.log('Radius : '+ radius);
var ctx = clock.getContext('2d');
ctx.beginPath();
ctx.arc(width/2,height/2,radius,0,Math.PI*2);
ctx.stroke();
}
您可以首先使用所有画布定义一个数组:
/// store references to element directly - define in global scope
var canvasArray = [
document.getElementById('clock1'),
document.getElementById('clock2'),
document.getElementById('clock3'),
document.getElementById('clock4'),
document.getElementById('clock5')
]
现在,这将保留对每个时钟画布的引用,因此我们不必每次都查找它们。
然后参考。您上一个问题,我们可以将大小调整代码与绘制代码分开:
function resizeCanvases() {
/// iterate array and update each canvas' bitmap according to CSS size
for(var i = 0, c; c= canvasArray[i]; i++) {
var style = getComputedStyle(c);
c.width = parseInt(style.getPropertyValue("width"),10);
c.height = parseInt(style.getPropertyValue("height"),10);
}
draw(canvasArray);
}
/// initial call when code starts
resizeCanvases();
/// update when window resizes (remember to redraw as well)
window.addEventListener('resize', resizeCanvases, false);
现在我们可以专注于绘制代码:
function draw(clocks) {
var clock,
ctx,
width, height,
radius,
i = 0;
for(; clock = clocks[i]; i++) {
/// get dimension of this canvas - remember to subtract line width
width = clock.width;
height = clock.height;
/// get radius
radius = Math.min(width, height) * 0.5;
/// draw circle
ctx = clock.getContext('2d');
ctx.beginPath();
ctx.arc(width/2,height/2,radius,0,Math.PI*2);
ctx.stroke();
}
}
然后致电:
draw(canvasArray);
需要的时候。
更新资料
参考 图片中的问题。我有这个结果:
我稍微修改了CSS,但是它不会影响外观,但是使重排效果更好:
.all
{
width:30%;
height:45%;
display:inline-block;
/*float:left;*/
}
以及:
html, body {
width:100%;
height:100%;
margin:0;
overflow:hidden;
}
Chrome似乎在CSS上有问题(或者getComputedStyle()
在这种情况下可能是个问题),而在Firefox和Opera中却可以正常工作。
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句