代碼(內含注釋)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="svg-wrap">
<svg width="200" height="200" xmlns='http://www.w3.org/2000/svg'>
<rect width="200" height="200" style="fill:#ddd"></rect>
</svg>
</div>
<canvas id="canvas"></canvas>
<script>
window.onload = function(){
//獲取svg內容
var svg = document.getElementById('svg-wrap').innerHTML;
var canvas = document.getElementById('canvas');
var c = canvas.getContext('2d');
//新建Image對象
var img = new Image();
//svg內容
img.src = 'data:image/svg+xml,' + unescape(encodeURIComponent(svg));//svg內容中可以有中文字符
img.src = 'data:image/svg+xml,' + svg;//svg內容中不能有中文字符
//svg編碼成base64
img.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svg)));//svg內容中可以有中文字符
img.src = 'data:image/svg+xml;base64,' + window.btoa(svg);//svg內容中不能有中文字符
//圖片初始化完成后調用
img.onload = function() {
//將canvas的寬高設置為圖像的寬高
canvas.width = img.width;
canvas.height = img.height;
//canvas畫圖片
c.drawImage(img, 0, 0);
//將圖片添加到body中
document.body.appendChild(img)
}
}
</script>
</body>
</html>
效果圖
svg標簽一定要加屬性
xmlns='http://www.w3.org/2000/svg'
svg標簽一定要加屬性xmlns='http://www.w3.org/2000/svg'
svg標簽一定要加屬性xmlns='http://www.w3.org/2000/svg'
不然svg內容和base64添加到img.src
會出錯,canvas和image都不會在頁面顯示出來