我试图绘制一些圈子,这些圈子都具有相同的属性,但是一个不同的结尾角色,我不想写整个圆圈代码5次,有没有办法分配大多数类的代码,只需为5个不同的ID更改一个变量?
以下是两个圈子
var canvas = document.getElementById('firefox');
var context = canvas.getContext('2d');
context.beginPath();
context.arc(64, 64, 60, 1.5*Math.PI, .3*Math.PI, true);
context.lineWidth = 8;
context.lineCap = "round";
context.strokeStyle = '#c5731e';
context.stroke();
var canvas = document.getElementById('chrome');
var context = canvas.getContext('2d');
context.beginPath();
context.arc(64, 64, 60, 1.5*Math.PI, .9*Math.PI, true);
context.lineWidth = 8;
context.lineCap = "round";
context.strokeStyle = '#c5731e';
context.stroke();
.3 * Math.PI和.9 * Math.PI是圈子之间唯一会改变的东西,我可以用任何方式写上面的内容所以我不必全部写5次?
答案 0 :(得分:3)
您无需更改标记,您可以这样做:
['firefox','chrome'].forEach(function(id, index){
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');
context.beginPath();
context.arc(64, 64, 60, 1.5*Math.PI, (index+1)*0.3*Math.PI, true);
context.lineWidth = 8;
context.lineCap = "round";
context.strokeStyle = '#c5731e';
context.stroke();
});
您不必复制代码或调用函数,只需在数组中添加元素即可。
如果无法从索引推断出角度,那么,
在后一种情况下,您可以执行以下操作:
var data = [
{id:'firefox', angle:33},
{id:'chrome', angle:43}
];
data.forEach(function(e){
var canvas = document.getElementById(e.id);
var context = canvas.getContext('2d');
context.beginPath();
context.arc(64, 64, 60, 1.5*Math.PI, e.angle, true);
context.lineWidth = 8;
context.lineCap = "round";
context.strokeStyle = '#c5731e';
context.stroke();
});
答案 1 :(得分:1)
创建一个函数,例如。;
function drawCanvas(size1, size2, id)
{
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');
context.beginPath();
context.arc(64, 64, 60, size1*Math.PI, size2*Math.PI, true);
context.lineWidth = 8;
context.lineCap = "round";
context.strokeStyle = '#c5731e';
context.stroke();
}
打五次电话