我想要做的就是这个
$.each($(".canvas"), function(n) {
var canvas = $(this)[0].getContext("2d");
canvas.drawImage(options[n]);
});
其中options是一个参数数组,但无法弄清楚如何格式化数组以使其工作
显然不是
['img, 0, 0, 70, 17, 21, 16, 70, 17', 'img, 0, 0, 80, 12, 21, 16, 70, 17']
这两个
[''+img+', 0, 0, 70, 17, 21, 16, 70, 17', ''+img+', 0, 0, 80, 12, 21, 16, 70, 17']
也不是这个
{0: [img, 0, 0, 70, 17, 21, 16, 70, 17]}
这不起作用
var options = [[img, 0, 0, 70, 17, 21, 16, 70, 17],
[img, 0, 16, 70, 17, 21, 16, 70, 17],
[img, 0, 32, 70, 17, 21, 16, 70, 17],
[img, 0, 48, 70, 17, 21, 16, 70, 17]];
img.onload = function() {
$.each($(".canvas"), function(n) {
var canvas = $(this)[0].getContext("2d");
canvas.drawImage(options[n].join(', '));
});
};
错误总是未捕获TypeError:输入错误或未捕获TypeError:非法调用
答案 0 :(得分:4)
canvas.drawImage.apply(canvas, options[n]);
options[n]
看起来像
[img, 0, 0, 70, 17, 21, 16, 70, 17]
完整示例:
var options = [[img, 0, 0, 70, 17, 21, 16, 70, 17],
[img, 0, 16, 70, 17, 21, 16, 70, 17],
[img, 0, 32, 70, 17, 21, 16, 70, 17],
[img, 0, 48, 70, 17, 21, 16, 70, 17]];
$(img).load(function()
{
$(".canvas").each(function(n)
{
var canvas = this.getContext('2d');
canvas.drawImage.apply(canvas, options[n]);
});
});