可能重复:
jQuery 等价于获取 Canvas 的上下文
我的问题是:
1)为什么注释代码的行为不像上面那样(即为什么会抛出错误)?
$(function () {
$('#ex4').append('<canvas class=can ></canvas>');
$('#ex4').append('<canvas class=can ></canvas>');
$('#ex4').append('<canvas class=can ></canvas>');
$('#ex4 canvas').each(function (index, element) {
$(this).attr("width", "125")
$(this).attr("height", "50")
var context = element.getContext("2d");
//var context = $(this).getContext("2d"); error
context.strokeStyle = "red";
context.fillStyle = "#999900";
context.font = "30px Arial";
context.fillText("HTML5", 0, 35);
});
})
2)我如何解决下面类似代码中的错误(大概与上面相同)?
$.each(data[0], function (i) {
$('#content').append('<canvas id=' + i + ' class=can ></canvas>');
$('#content #' + i).attr("width", "125")
$('#content #' + i).attr("height", "50")
//var context = $('#content #'+i).getContext("2d"); error
})