1

I have a set of coordinates and for every pair I'd like to place a SVG on the canvas. The problem is in getCircle function. The SVG doesn't work, but if I draw a circle(see commented code) it works.

function getCircle() {
  var circle = document.createElement("canvas"),
      ctx = circle.getContext("2d"),      
      r2 = radius + blur;

  circle.width = circle.height = r2 * 2;

/*
  ctx.shadowOffsetX = ctx.shadowOffsetY = r2 * 2;
  ctx.shadowBlur = blur;
  ctx.shadowColor = "purple";

  ctx.beginPath();
  ctx.arc(-r2, -r2, radius, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.fill(); 
*/
  
  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, 0, 0);
  };
  img.src = "https://upload.wikimedia.org/wikipedia/en/0/09/Circle_Logo.svg";
  
  return circle;
}

var radius = 5;
var blur = 1;
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
var circle = getCircle();
ctx.clearRect(0, 0, canvas.width, canvas.height);

var data = [[38,20,2]];

for (var i = 0, len = data.length, p; i < len; i++) {
  p = data[i];
  ctx.drawImage(circle, p[0] - radius, p[1] - radius);
}
#c { 
  width: 400px;
  height: 200px;
}
<canvas id="c"></canvas>
Bacchus
  • 515
  • 8
  • 22
  • you want to draw that image on canvas? – Durga Jul 31 '17 at 13:26
  • @Durga - yes, it's a `for` loop which draws that image at the bottom of the code. – Bacchus Jul 31 '17 at 13:32
  • you want for svg image only or can use jpg/png? – Durga Jul 31 '17 at 13:36
  • @Durga - Just SVG. – Bacchus Jul 31 '17 at 13:39
  • 1
    your getCircle function will return you an empty canvas, on which your image (btw it doesn't matter that it is an svg here), will only be drawn once all other operations will have ended. Which means that at the time your code kicks in the for loop, the canvas that you do draw is still empty. – Kaiido Jul 31 '17 at 14:07
  • @Kaiido I did draw images at given position, is it possible to wait until that image load and then return from given function ? – Durga Jul 31 '17 at 14:14
  • Read the duplicate I linked you to. Use callbacks, you're not far from here. – Kaiido Jul 31 '17 at 14:16

1 Answers1

0

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 200;
var data = [[0,20,2],[125,20,2],[250,20,2]];
drawImage();

function drawImage() {
  var img = new Image();
  img.onload = function() {
    for (var i = 0, len = data.length, p; i < len; i++) {
       p = data[i];
       ctx.drawImage(this, p[0] , p[1] , 150, 150);
     }
  };
  img.src = "https://upload.wikimedia.org/wikipedia/en/0/09/Circle_Logo.svg";
}
#c { 
  width: 400px;
  height: 200px;
}
<canvas id="c"></canvas>

in img.onload() draw your image in specified position with widht and height using drawImage().

Durga
  • 15,263
  • 2
  • 28
  • 52