我有一个html页面,我需要在其中添加多个canvas元素并将其加载到页面加载中。
function draw()
{
var c=document.getElementById("myCanvas");
var padding = 20;
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,175,50);
grd.addColorStop(0,"#E05D1B");
grd.addColorStop(1,"#00FF00");
ctx.fillStyle=grd;
ctx.fillRect(0,0,275,50);
}
<canvas id="myCanvas" width="250" height="8" style="margin-bottom:10px;margin-left:10px;">
<img src="images\gradient1.png" style="margin-bottom:10px;margin-left:10px;"/>
</canvas>
我添加了这个代码与不同的ID,但我需要重新编码javascript;我怎么能减少它?
<canvas id="myCanvas1" width="250" height="8" style="margin-bottom:10px;margin-left:10px;"> <img src="images\gradient1.png" style="margin-bottom:10px;margin-left:10px;"/> </canvas>
答案 0 :(得分:5)
您可以将单独的画布元素的上下文作为参数传递给绘制函数(fiddle):
function draw(ctx)
{
var grd=ctx.createLinearGradient(0,0,175,50);
grd.addColorStop(0,"#E05D1B");
grd.addColorStop(1,"#00FF00");
ctx.fillStyle=grd;
ctx.fillRect(0,0,275,50);
}
draw(document.getElementById("canvas_1").getContext("2d"));
draw(document.getElementById("canvas_2").getContext("2d"));
或者,根据您拥有的画布元素的数量,在循环(fiddle)上调用绘图函数可能更有效:
function draw(ctx)
{
var grd=ctx.createLinearGradient(0,0,175,50);
grd.addColorStop(0,"#E05D1B");
grd.addColorStop(1,"#00FF00");
ctx.fillStyle=grd;
ctx.fillRect(0,0,275,50);
}
var i = 1;
while (document.getElementById("canvas_" + i)) {
draw(document.getElementById("canvas_" + i).getContext("2d"));
i ++;
}