javascript - 在单个 HTML 页面中绘制多个 HTML Canvas 元素

标签 javascript html canvas

我有一个 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/

相关文章:

javascript - 如何对 L.canvas 渲染器上绘制的传单标记进行动画处理?

javascript - 如何在 Canvas 中找到填充文本的起点和终点

javascript - 使用带有 onclick 事件的 Javascript 启动 CSS3 动画

javascript - 从 VueJS 中的 API 获取后更新 DOM

html - css)我想将页脚放在该部分下,但它在旁边,在文章旁边

html - 使用 css 绘制一个简单的列

javascript - 数据 URI 在 Firefox 上不显示

javascript - 为什么我的图片隐藏了页脚?

javascript - 如何在 three.js/WebGL 中更改 STL 对象的不透明度?

html - 将图像和文本对齐在同一行