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
asked Jul 10, 2011 at 14:46
fxck
4,9088 gold badges59 silver badges97 bronze badges
1 Answer 1
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]);
});
});
answered Jul 10, 2011 at 14:51
Matt Ball
361k102 gold badges655 silver badges725 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Felix Kling
options has to have the right structure though. And img must be a DOM element afaik.Felix Kling
@foxx: You have to use
canvas.drawImage.apply(canvas, options[n]); (pass canvas as first argument).fxck
lovely, did try apply() before, but with this instead of canvas, stupid me, thanks
lang-js
drawImagetakes several arguments, not just one which is a string.foo(a, b)is different thanfoo('a, b'). Only because there a commas in the string does not make it a list of arguments.