来源:https://github.com/canvg/canvg
Include the following files in your page:
<script type="text/javascript" src="http://canvg.github.io/canvg/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.github.io/canvg/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.github.io/canvg/canvg.js"></script>
Put a canvas on your page
<canvas id="canvas" width="1000px" height="600px"></canvas>
Example canvg calls:
<script type="text/javascript">
window.onload = function() {
//load '../path/to/your.svg' in the canvas with id = 'canvas'
canvg('canvas', '../path/to/your.svg')
//load a svg snippet in the canvas with id = 'drawingArea'
canvg(document.getElementById('drawingArea'), '<svg>...</svg>')
//ignore mouse events and animation
canvg('canvas', 'file.svg', { ignoreMouse: true, ignoreAnimation: true })
}
</script>
The third parameter is options:
You can call canvg without parameters to replace all svg images on a page. See the example.
There is also a built in extension method to the canvas context to draw svgs similar to the way drawImage works:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg(SVG_XML_OR_PATH_TO_SVG, dx, dy, dw, dh);
自己将canvans转svg的两种实现方式:
//直接svgBase64转Png
/* function getBase64PNG(svgStr,themeSize) {
var image = new Image();
image.src = svgStr;
var canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 300;
var ctx = canvas.getContext("2d");
if(themeSize==3){
ctx.drawImage(image, 0, 0);
}else if(themeSize==2){
ctx.drawImage(image, 50, 50);
}else if(themeSize==1){
ctx.drawImage(image, 100, 100);
}
var dataURL = canvas.toDataURL("image/png");
return dataURL
} */
/**
*直接svg转Png的pngBase64
*/
function getBase64PNG(svgStr,themeSize) {
var canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 300;
var ctx = canvas.getContext("2d");
if(themeSize==3){
ctx.drawSvg(svgStr, 0, 0, 300, 300);
}else if(themeSize==2){
ctx.drawSvg(svgStr, 50, 50, 200, 200);
}else if(themeSize==1){
ctx.drawSvg(svgStr, 100, 100, 100, 100);
}
var dataURL = canvas.toDataURL("image/png");
return dataURL
}
<script type="text/javascript">
var url="https://www.czxiu.com/assets/z/2017jiehunzheng/15/2f43b42fd833d1e77420a8dae7419000.gif";
$(document).ready(function() {
initCavans(url);
});
//初始化canvans
var cavans;
function initCavans(pngPath){
var image = new Image();
image.src = pngPath;
image.οnlοad=function(){
cavans = new fabric.Canvas('cer');
cavans.width=image.width;
cavans.height=image.height;
alert(image.width);
alert(image.height);
}
}
</script>