我在字串中有一個 svg,如下所示:
const svgString = (color) => `<svg height="150" width="500">
<ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
<ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
<ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;
請考慮這是一個 svg 示例,真正的 svg 更大且更復雜,因此不要過多關注該示例。
我想要的是在畫布上繪制那個 SVG 字串。我嘗試過這樣的事情:
const canvas = document.createElement('canvas');
canvas.width = 18;
canvas.height = 25;
const ctx = canvas.getContext('2d');
const path = new Path2D(svgString('red'));
ctx.drawImage(path, 0, 0, 18, 25);
但這失敗并出現以下錯誤:
"<a class='gotoLine' href='#52:5'>52:5</a> Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement or HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or SVGImageElement or VideoFrame)'."
知道如何解決這個問題嗎?
const svgString = (color) => `<svg height="150" width="500">
<ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
<ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
<ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;
const canvas = document.createElement('canvas');
canvas.width = 18;
canvas.height = 25;
const ctx = canvas.getContext('2d');
const path = new Path2D(svgString('red'));
ctx.drawImage(path, 0, 0, 18, 25);
uj5u.com熱心網友回復:
這里有兩個例子。在這兩個示例中,我都將 SVG 命名空間添加到字串中,因為它是一個單獨的 XML/SVG 檔案,而不是 HTML 的一部分。
在第一個示例中,我只是創建了一個資料 URL 并將其作為影像物件的源插入。這里需要設定寬度和高度。
在第二個示例中,我使用了 Blob 和函式URL.createObjectURL()。
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
const svgString = (color) => `<svg xmlns="http://www.w3.org/2000/svg" height="150" width="500">
<ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
<ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
<ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;
var img = new Image();
img.width = 500;
img.height = 150;
img.addEventListener('load', e => {
ctx.drawImage(e.target, 0, 0);
});
img.src = `data:image/svg xml,${svgString('red')}`;
<canvas width="500" height="150" id="canvas"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
const svgString = (color) => `<svg xmlns="http://www.w3.org/2000/svg" height="150" width="500">
<ellipse cx="240" cy="100" rx="220" ry="30" style="fill:${color}" />
<ellipse cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
<ellipse cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
</svg>`;
var svg = new Blob([svgString('red')], {
type: "image/svg xml;charset=utf-8"
});
var url = URL.createObjectURL(svg);
var img = new Image();
img.addEventListener('load', e => {
ctx.drawImage(e.target, 0, 0);
URL.revokeObjectURL(url);
});
img.src = url;
<canvas width="500" height="150" id="canvas"></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437793.html
標籤:javascript html svg 帆布
