Reputation: 4908
what I'm trying to do is this
$.each($(".canvas"), function(n) {
var canvas = $(this)[0].getContext("2d");
canvas.drawImage(options[n]);
});
where options would be an array of arguments, but can't figure out how should the array be formatted for it to work
obviously not
['img, 0, 0, 70, 17, 21, 16, 70, 17', 'img, 0, 0, 80, 12, 21, 16, 70, 17']
this neither
[''+img+', 0, 0, 70, 17, 21, 16, 70, 17', ''+img+', 0, 0, 80, 12, 21, 16, 70, 17']
nor this
{0: [img, 0, 0, 70, 17, 21, 16, 70, 17]}
this would not work either
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(', '));
});
};
the error is alway Uncaught TypeError: Type error or Uncaught TypeError: Illegal invocation
Upvotes: 2
Views: 422
Reputation: 360056
Use Function.apply
.
canvas.drawImage.apply(canvas, options[n]);
Where options[n]
looks something like
[img, 0, 0, 70, 17, 21, 16, 70, 17]
Full example:
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]);
});
});
Demo: http://jsfiddle.net/mattball/5EQbC/
Upvotes: 4