Tra*_*ler 1 jquery html5 canvas
我想不止一次使用这个camvas对象,但我只能在引用#ID时使它工作.这是我的代码
function bubbleArrow() {
var canvasId = 'triangleTwo',
canvas = document.getElementById(canvasId),
ctx = canvas.getContext('2d');
// Draw triangle
ctx.fillStyle="#f0f1f1";
ctx.beginPath();
// Draw a triangle location for each corner from x:y 100,110 -> 200,10 -> 300,110 (it will return to first point)
ctx.moveTo(100,110);
ctx.lineTo(100,150);
ctx.lineTo(150,110);
ctx.closePath();
ctx.fill();
}
Run Code Online (Sandbox Code Playgroud)
当我只需要使用一次时,这很好用.我想通过className引用我的画布,以便在我的dom中多次使用它.
function bubbleArrow() {
var canvasName = $('.triangleTwo'),
ctx = canvas.getContext('2d');
ctx.fillStyle="#f0f1f1";
ctx.beginPath();
ctx.moveTo(100,110);
ctx.lineTo(100,150);
ctx.lineTo(150,110);
ctx.closePath();
ctx.fill();
}
Run Code Online (Sandbox Code Playgroud)
当我通过类名定位我的画布时,请帮助解释为什么它不起作用,但是当用#id定位它时它会起作用.谢谢
你可以尝试这样的事情:
var canvases = document.getElementsByClassName('triangleTwo')
for (var i = 0; i < canvases.length; i ++) {
var ctx = canvases[i].getContext('2d')
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
或者,使用jQuery:
$('.triangleTwo').each(function() {
var ctx = this.getContext('2d')
// stuff
})
Run Code Online (Sandbox Code Playgroud)