Reputation: 1119
I have multiple canvases, each with data-id attribute that is used to retrieve the dataURL in order to draw the image like so:
<canvas data-id='2' class='drawing-result>
The following will only put them all in the last canvas:
var $canvases = $(".drawing-result");
for (var i=0; i<$canvases.length; i++){
var canvas = $canvases.get(i);
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(this, 0, 0);
};
// skipping the code for retrieving dataURL using data-id
imageObj.src = dataURL;
I suspect it may have to do with shallow copying some things, but that can't be the case because I put var everywhere.
Upvotes: 0
Views: 816
Reputation: 220136
JavaScript's var
variable declaration is function scoped, not block scoped. Your context
is being overwritten every time the loop runs.
Instead of that for-loop, use jQuery's .each()
function:
$(".drawing-result").each(function (i, canvas) {
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(this, 0, 0);
};
// skipping the code for retrieving dataURL using data-id
imageObj.src = dataURL;
});
Upvotes: 2