<center><canvas id=c1 width=400 height=400></canvas>
<script>
ctx = c1.getContext('2d')
ctx.fillStyle = '#7ef' // draw blue background with the darker frame
ctx.fillRect(0, 0, 400, 400)
ctx.fillStyle = '#9ff'
ctx.fillRect(10, 10, 400-20, 400-20)
var X = 75, W = 50, G = 20
ctx.lineWidth = 10
var colors = ['blue', 'black', 'red', 'yellow', 'green']
var args = [
[X,X,W],
[X+W+W+G,X,W],
[X+W+W+G+W+W+G,X,W],
[X+W+G/2,X+W,W],
[X+W+G/2+W+W+G,X+W,W]]
while (colors.length > 0) {
ctx.strokeStyle = colors.shift()
ctx.beginPath()
ctx.arc.apply(ctx, args.shift().concat([0,Math.PI*2,true]))
ctx.stroke()
}
</script>
以上是我此时的代码。我的目标是逗 child ,有12岁的男孩,但我的代码不够神奇,是否可以通过删除所有手写坐标来让它不那么无聊?使环“互连”也很酷,但如何实现呢?
这是我当前代码的输出:
奥运五环应该是这样的:
最佳答案
对于 12 岁的 child !
我为您编写了一些代码,这些代码不一定无聊或有趣、简单或困难,但它可以完成工作:
var canvas = document.getElementById('c1').getContext('2d');
var radius = 50;
var circles = [
{
color:'blue',
x : 2*radius - radius/2,
y : 2*radius,
isTop: true
} , {
color:'black',
x : 4*radius,
y : 2*radius,
isTop: true
} , {
color:'red',
x : 6*radius + radius/2,
y : 2*radius,
isTop: true
} , {
color:'yellow',
x : 3*radius - radius/4,
y : 3*radius,
isTop: false
} , {
color:'green',
x : 5*radius + radius/4,
y : 3*radius,
isTop: false
}
];
function drawArc(canvas, color, x, y, start, end) {
if (color !== 'white') drawArc(canvas, 'white', x, y, start, end);
canvas.lineWidth = color === 'white' ? 16 : 10;
canvas.strokeStyle = color;
canvas.beginPath();
canvas.arc(x, y, radius, start - Math.PI/2, end - Math.PI/2, true);
canvas.stroke();
}
circles.forEach(function(circle){
drawArc(canvas, circle.color, circle.x, circle.y, 0, Math.PI*2);
});
circles.forEach(function(circle){
if (circle.isTop) {
drawArc(canvas, circle.color, circle.x, circle.y, Math.PI, Math.PI*2/3);
drawArc(canvas, circle.color, circle.x, circle.y, Math.PI*5/3, Math.PI*4/3);
} else {
drawArc(canvas, circle.color, circle.x, circle.y, 0, Math.PI/3);
drawArc(canvas, circle.color, circle.x, circle.y, Math.PI*2/3, Math.PI/3);
}
});
http://jsbin.com/IrOJOhIg/1/edit
如果我要解释代码,我会从 circles 变量开始,它是一个数组,表示每个圆的颜色、中心以及它是否在顶行。我会注释掉 += radius/2
和 radius/4
部分并为它们运行代码,显示圆圈在一起太紧,并取消注释它们以显示改变 x 坐标会使它们分开。
然后我将解释 drawArc
函数,该函数以不同的线宽绘制圆的一部分,首先是白色,然后是实际颜色。这几乎是整个脚本中最困难的部分。
最后,我将再次运行脚本并注释掉最后的 forEach,以显示最后绘制的环完全覆盖了之前的环并向 12 岁的 children 寻求解决方案。您应该寻求的解决方案是分段绘制圆圈。
我已将圆圈从顶部开始分成 6 block ,如果您仔细看一下它们,您会发现无论圆圈是否在顶行,相同的部分都可以被覆盖或在顶部。 each 的 final 重绘每个圆的 2 个部分,这些部分必须位于交叉点的顶部。
最后,如果 12 岁的 child 注意到我的代码中的交叉点实际上是颠倒的,那么奖励加分,而对于提出解决方案的人来说,奖励加分更多。 (显然,最简单的解决方案是摆弄最后一个 forEach)。编辑:实际上只是将条件设置为 !circle.isTop
更简单。
PS:存在一些舍入误差,导致圆弧相交处出现细白线。它们可以修复,但我没有理会它们。
关于javascript - 在 HTML5 Canvas 上使用 JavaScript 的奥运五环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21180453/