2017-07-31 253 views
0

我有一組座標,並且希望在畫布上放置SVG。問題在於getCircle函數。 SVG不起作用,但是如果我繪製一個圓圈(請參閱註釋代碼),它可以工作。在畫布上繪製SVG

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>

+0

要在畫布上繪製該圖像? – Durga

+0

@Durga - 是的,它是一個'for'循環,它在代碼底部繪製該圖像。 – Bacchus

+0

只需要svg圖片或可以使用jpg/png? – Durga

回答

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>

img.onload()繪製圖像與使用drawImage() widht和高度指定位置。