我有一个 html 页面,我需要在其中添加 1 个以上的 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>
最佳答案
您可以将单独 Canvas 元素的上下文作为参数传递给绘图函数 (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"));
或者,根据您拥有的 Canvas 元素数量,循环调用绘制函数可能更有效 (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 ++;
}
关于javascript - 在单个 HTML 页面中绘制多个 HTML Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10630735/