2

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

1
  • 1
    drawImage takes several arguments, not just one which is a string. foo(a, b) is different than foo('a, b'). Only because there a commas in the string does not make it a list of arguments. Commented Jul 10, 2011 at 14:54

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

3 Comments

options has to have the right structure though. And img must be a DOM element afaik.
@foxx: You have to use canvas.drawImage.apply(canvas, options[n]); (pass canvas as first argument).
lovely, did try apply() before, but with this instead of canvas, stupid me, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.