Để vẽ nội dung SVG lên Canvas, bạn cần chuyển SVG thành đối tượng Image, sau đó dùng drawImage() để vẽ lên canvas. Cách phổ biến: dùng <foreignObject> trong SVG để nhúng HTML, tạo Blob SVG, tạo Object URL, gán vào Image.src, đợi onload rồi vẽ.
Ví dụ
Mã sau minh họa quy trình đầy đủ:
<!DOCTYPE html>
<html>
<head>
<title>SVG file on HTML Canvas</title>
</head>
<body>
<canvas id="myCanvas" style="border:2px solid green;" width="300" height="300"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="https://www.w3.org/2000/svg" width="300" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="https://www.w3.org/1999/xhtml" style="font-size:50px">' +
'Simply Easy ' +
'<span style="color:blue;">Learning</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img1 = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);
img1.onload = function() {
ctx.drawImage(img1, 25, 70);
DOMURL.revokeObjectURL(url);
}
img1.src = url;
</script>
</body>
</html>
Lưu ý: CORS và chính sách bảo mật có thể chặn việc vẽ SVG từ nguồn khác domain. Đảm bảo SVG cùng origin hoặc có header CORS phù hợp.