02 程式碼下載成SVG圖檔
(2023/06/17)
由於新的圖書印刷所需,之前提供的程式圖檔,都是直接利用【按右鍵】/【下載圖片】
但下載下來的圖片解析度不高,不適合印刷!
所以向Webduino求救,Marty教我用如下的方法:
直接在瀏覽器 console 貼下面這段 js
var DOMURL = self.URL || self.webkitURL || self;
function svg(){
canvas = Blockly.mainWorkspace.svgBlockCanvas_.cloneNode(true);
if (canvas.children[0] === undefined) throw "Couldn't find Blockly canvas."
canvas.removeAttribute("transform");
var css = '<defs><style type="text/css" xmlns="http://www.w3.org/1999/xhtml"><![CDATA[' + Blockly.Css.CONTENT.join('') + ']]></style></defs>';
var bbox = document.getElementsByClassName("blocklyBlockCanvas")[0].getBBox();
var content = new XMLSerializer().serializeToString(canvas);
xml = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="'
+ bbox.width + '" height="' + bbox.height + '" viewBox=" ' + bbox.x + ' ' + bbox.y + ' ' + bbox.width + ' ' + bbox.height + '">' +
css + '">' + content + '</svg>';
return new Blob([xml], { type: 'image/svg+xml;base64' });
}
function download(url, filename){
let element = document.createElement('a')
element.href = url
element.download = filename;
element.click();
DOMURL.revokeObjectURL(element.href)
}
function exportSVG() {
download(DOMURL.createObjectURL(svg()),'blocks.svg');
}
function exportPNG(){
var img = new Image();
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 600;
canvas.getContext("2d").drawImage(img, 0, 0);
download(canvas.toDataURL("image/png"),'blocks.png');
};
img.src = DOMURL.createObjectURL(svg());
}
exportSVG()
步驟如下: