Exporting block as png

456 views
Skip to first unread message

Shiva sandupatla

unread,
Aug 29, 2020, 6:19:43 AM8/29/20
to Blockly
Hi, all.

I have tried to export certain block as png using following code 

init: function() {
this.jsonInit(
            {
                "type": "buttonenabled",
                "message0": "set %1 enabled to %2",
                "args0": [
                  {
                    "type": "field_dropdown",
                    "name": "setbtnenabledoption",
                    "options": [
                      [
                        "button1",
                        "button1"
                      ],
                      [
                        "button2",
                        "button2"
                      ],
                      [
                        "button3",
                        "button3"
                      ]
                    ]
                  },
                  {
                    "type": "input_value",
                    "name": "setbtnenabled",
                    "check": "Boolean"
                  }
                ],
                "previousStatement": null,
                "nextStatement": null,
                "colour": 135,
                "tooltip": "It is used to enable/disable the button.",
                "helpUrl": ""
              }
        );
 
  },
  customContextMenu: function(options) {
    var option = {enabled: true};
           option.text = "Export block as png";
           option.callback = function() {
          



             
var scaleFactor = 1;


var cp = Blockly.mainWorkspace.svgBlockCanvas_.cloneNode(true);
cp.removeAttribute("width");
cp.removeAttribute("height");
cp.removeAttribute("transform");


var styleElem = document.createElementNS("http://www.w3.org/2000/svg", "style");

styleElem.textContent = Blockly.Css.CONTENT.join('') + ".blocklyToolboxDiv {background: rgba(0, 0, 0, 0.05);}.blocklyMainBackground {stroke:none !important;}.blocklyTreeLabel, .blocklyText, .blocklyHtmlInput {font-family:'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace !important;}.blocklyText { font-size:1rem !important;}.rtl .blocklyText {text-align:right;} .blocklyTreeLabel { font-size:1.25rem !important;} .blocklyCheckbox {fill: #ff3030 !important;text-shadow: 0px 0px 6px #f00;font-size: 17pt !important;}";
cp.insertBefore(styleElem, cp.firstChild);


var bbox = Blockly.mainWorkspace.svgBlockCanvas_.getBBox();
var xml = new XMLSerializer().serializeToString(cp);
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 + '"><rect width="100%" height="100%" fill="white"></rect>'+xml+'</svg>';

var svgBase64 = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(xml)));
var img = document.createElement('img');
img.src = svgBase64;



var canvas = document.getElementById('img');
canvas.width = Math.ceil(bbox.width) * scaleFactor;
canvas.height = Math.ceil(bbox.height) * scaleFactor;
var ctx = canvas.getContext('2d');
ctx.scale(scaleFactor, scaleFactor);




  ctx.drawImage(img, 0, 0);




window.open(canvas.toDataURL(), '_blank');


  






           };
           options.push(option);
  }


But I am getting strange image

download.png

I need to get the original block but unable to get it. 

Is there any corrections in the code or any another method to do so.

Hoping with a positive response

Beka Westberg

unread,
Aug 29, 2020, 10:34:51 AM8/29/20
to blo...@googlegroups.com
Hello,

Sam actually implemented a function for downloading screenshots of the workspace a while ago :D Here is the source code for it.

But be warned he stated in the pull request:
> Only supporting Chrome at this point, and only blocks on the workspace, this is meant for testing and not a feature ready for production.

So it doesn't work on all browsers, and may be buggy, but hopefully it gives you a place to start!
--Beka

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/blockly/fcd2e193-9f7f-403d-be0c-a1d0b25b860en%40googlegroups.com.

suryaprakash lokula

unread,
Aug 30, 2020, 1:31:57 AM8/30/20
to Blockly
ok i had tried it but image is not as the block in workspace but it is almost equal to the blockl image what can we do to make it equal to the block image

Abby Schmiedt

unread,
Sep 1, 2020, 6:53:55 PM9/1/20
to Blockly
Hello!

I am not entirely sure what the question is. Could you clarify what you mean by 'make it equal to the block image'? 

Thanks!
Abby

suryaprakash lokula

unread,
Sep 2, 2020, 7:39:48 AM9/2/20
to Blockly
Hai i found the solution of export the block as png in neet and clear format that worked for me well u can also try it


 var id = Blockly.selected.id;

  var canvasSVG =workspace.blockDB_[id].svgGroup_;
  


             var DOMURL = self.URL || self.webkitURL || self;

             function svg() {
                 canvas = canvasSVG.cloneNode(true);
                 canvas.setAttribute('class','blocklyDraggable');
                 if (canvas.children[0] === undefined) throw "Couldn't find Blockly canvas."
             
                 canvas.removeAttribute("transform");
             
                 var cssContent = Blockly.Css.CONTENT.join('');
             
                 cssContent += ".blocklyConnectionIndicator{display:none;} .blocklyEditableText text.blocklyText{fill: #575E75;}";
             
                 var css = '<defs><style type="text/css" xmlns="http://www.w3.org/1999/xhtml"><![CDATA[' + cssContent + ' ]]></style></defs>';
             
                 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="' +
                 workspace.blockDB_[k].width + '" height="' +  workspace.blockDB_[k].height + '" viewBox=" ' + 0+ ' ' + 0+ ' ' + workspace.blockDB_[k].width + ' ' + workspace.blockDB_[k].height + '">' +
                     css + '">' + content + '</svg>';
             
                 if (xml.includes('<use height="12px" width="12px" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#blocklyDropdownArrowSvg"')) {
             
                     while (xml.includes('<use height="12px" width="12px" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#blocklyDropdownArrowSvg"')) {
             
                         xml = xml.replace('<use height="12px" width="12px" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#blocklyDropdownArrowSvg" ', '<image xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" height="12px" width="12px" xlink:href="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEtLjQyTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiNmZmYiLz48L3N2Zz4=" ');
             
                     }
             
                 }
             
                 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 exportPNG() {
                 var img = new Image();
             
             
                 img.onload = function() {
                     var canvas = document.createElement('canvas');
                     canvas.width = workspace.blockDB_[k].width * 2.5 + 20;
                     canvas.height = workspace.blockDB_[k].height * 2.5 + 20;
             
                     canvas.getContext('2d').scale(2.5, 2.5);
             
                     canvas.getContext("2d").drawImage(img, 0, 0);
             //document.getElementById('id').setAttribute('src',canvas.toDataURL("image/png"));
                     download(canvas.toDataURL("image/png"), 'code.png');
                 };
                 img.src = DOMURL.createObjectURL(svg());
             }

             exportPNG();

suryaprakash lokula

unread,
Sep 3, 2020, 11:59:07 AM9/3/20
to Blockly
I found that it will not work with current blockly version 
Try with older ones

Reply all
Reply to author
Forward
0 new messages