Ionut Necula
Ionut Necula

Reputation: 11472

How to add images to each canvas?

I have 10 canvases on the same page. On each canvas I'm trying to add an existent image. Is this possible? I tried this next code but is not displaying any image:

var numberOfPages = $('.draw_pages canvas').length;
   var i = 0;
   var counter = 0;
   for(i=0; i<numberOfPages; i++){
	   counter++;
	   var canvas = document.getElementById("canvas_"+counter);
	   var ctx = canvas.getContext("2d");
	   ctx.font = "30px Arial";
	   ctx.fillText("Hello World "+ counter, 110, 250);
	   	
	   	//add images to canvas
	   	var base_image = new Image();
	   	base_image.onload = function(){
			init();
		}
		    base_image.src = '../images/page_1.png';
		function drawImage(){
		    ctx.drawImage(base_image, 0, 0, 575, 575);
		}
		function init(){
			drawImage();
		}
		
			
   }

I've also tried this way, but it works only when I hit enter key on the url of the browser and the text is being drawed:

var numberOfPages = $('.draw_pages canvas').length;
   var i = 0;
   var counter = 0;
   for(i=0; i<numberOfPages; i++){
	   counter++;
	   console.log(counter);
	   var canvas = document.getElementById("canvas_"+counter);
	   var ctx = canvas.getContext("2d");
	   ctx.font = "30px Arial";
	   ctx.fillText("Hello World "+ counter, 110, 250);
	   	
	   	//add images to canvas
	   	drawImage();
		function drawImage(){
		  base_image = new Image();
		  base_image.src = '../jester/images/page_1.png';
		  //base_image.onload = function(){
		    ctx.drawImage(base_image, 0, 0, 575, 575);
		  //}
		}
   }

Any ideas?

Upvotes: 4

Views: 63

Answers (1)

num8er
num8er

Reputation: 19372

Be simple! Use jquery .each() and do Your operations inside of it.

$(function() {
  $('canvas').each(function() {
      var n = $(this).attr('id').split('_')[1];
      var context = this.getContext('2d');
      var image = new Image();
      image.src = 'http://lorempixel.com/image_output/abstract-q-c-640-480-'+n+'.jpg';
      image.onload = function(){
        context.drawImage(image, 0, 0, 575, 575);
        context.font = '30px Arial';
        context.fillText('Hello World '+ n, 20, 20);      
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas_1"></canvas>
<canvas id="canvas_2"></canvas>
<canvas id="canvas_3"></canvas>

Upvotes: 5

Related Questions