gpt4 book ai didi

javascript - HTML5 Canvas - 按类在所有 Canvas 元素中绘制相同的东西

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:34 25 4
gpt4 key购买 nike

我有以下 HTML...

<body onload="draw();">

<p><a href=""><canvas class="demo2" width="6" height="12">Fallback</canvas> Back to (1)...</a></p>
<p><a href=""><canvas class="demo2" width="6" height="12">Fallback</canvas> Back to (2)...</a></p>

</body>

...和 ​​javascript:

function draw() {        
var canvas2 = $('.demo2').get(0); // This draws in the first canvas
//var canvas2 = $('.demo2').get(); This doesn't draw at all
if (canvas2.getContext) {
var ctx2 = canvas2.getContext('2d');

ctx2.beginPath();
ctx2.moveTo(6,0);
ctx2.lineTo(6,12);
ctx2.lineTo(0,6);
ctx2.fillStyle = 'rgb(0,100,220)';
ctx2.fill();
}
}

我想要发生的是所有具有 demo2 类的 Canvas 都被绘制。

我认为 $('.demo2').get() 会通过该类名获取所有元素。 $('.demo2').get(0) 绘制第一个,但我想绘制它们。

演示在 http://jsfiddle.net/kMN3s/

最佳答案

您可以使用.each 为每个.demo2 执行操作:http://jsfiddle.net/kMN3s/2/ .

function draw() {        
$('.demo2').each(function() {
if (this.getContext) { // `this` is an element each time
var ctx2 = this.getContext('2d');

ctx2.beginPath();
ctx2.moveTo(6,0);
ctx2.lineTo(6,12);
ctx2.lineTo(0,6);
ctx2.fillStyle = 'rgb(0,100,220)';
ctx2.fill();
}
});
}

关于javascript - HTML5 Canvas - 按类在所有 Canvas 元素中绘制相同的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8532686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com