Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <p>Select a solution in sequence, use mouse wheel to zoom in and out</p>  
<p>Red box is the viewport (initial stage size), blue is Konva Stage.</p>  
<p>Scale: <span id="scaleDisplay">1</span></p>
    <p>
      <input type="radio" class="solution" name="solutionNo" id="solution1" value="solution1" checked="on"><label for="solution1">Solution 1 - grid on stage</label><br />
      <input type="radio" class="solution" name="solutionNo" id="solution2" value="solution2"><label for="solution2">Solution 2 - grid on merged</label><br />
      <input type="radio" class="solution" name="solutionNo" id="solution3" value="solution3"><label for="solution3">Solution 3 - grid on merged inc fix for dancing grid effect</label><br />
      <input type="radio" class="solution" name="solutionNo" id="solution4" value="solution4" ><label for="solution4">Solution 4 - optimised drawing via clip function</label>       
    </p>
        <p id="buttons">
      <button id="saveDefault">
        Save viewport image
      </button>
      <button id="saveExtended">
        Save viewport plus 200px around
      </button>
    </p>
    <div id="container"></div>
              
            
!

CSS

              
                      body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #f0f0f0;
      }
      #container {
        width: 800px;
        height: 400px;
      }
p {
  margin: 4px;
}
#container {
  margin: 10px;
}
              
            
!

JS

              
                      var width = 800;
      var height = 400;
      var stage = new Konva.Stage({
        container: 'container',
        width: width,
        height: height,
        draggable: true,
      });

      var layer = new Konva.Layer();
      var gridLayer = new Konva.Layer({
        draggable: false,
        x: 0, 
        y: 0,
      });
      stage.add(gridLayer);

      /* The drawLines() function is a juntion where we configure the rects
      * then go on to execute the selected solution for the grid line drawing
      * process
      */
      let stageRect, viewRect, fullRect, gridAdjust, gridRect;
      const stepSize = 40; // set a value for the grid step gap.
      function drawLines(){
        
          gridLayer.clear();
          gridLayer.destroyChildren();
          gridLayer.clipWidth(null); // clear any clipping

          stageRect = {
            x1: 0, 
            y1: 0, 
            x2: stage.width(), 
            y2: stage.height(),
            offset: {
              x: unScale(this.stage.position().x),
              y: unScale(this.stage.position().y),
            }
          };
          viewRect = {
            x1: -stageRect.offset.x,
            y1: -stageRect.offset.y,
            x2: unScale(width) - stageRect.offset.x,
            y2: unScale(height) - stageRect.offset.y
          };
          // and find the largest rectangle that bounds both the stage and view rect.
          // This is the rect we will draw on.  
          fullRect = {
            x1: Math.min(stageRect.x1, viewRect.x1),
            y1: Math.min(stageRect.y1, viewRect.y1),
            x2: Math.max(stageRect.x2, viewRect.x2),
            y2: Math.max(stageRect.y2, viewRect.y2)          
          };
          gridOffset = {
            x: Math.ceil(unScale(this.stage.position().x) / stepSize) * stepSize,
            y: Math.ceil(unScale(this.stage.position().y) / stepSize) * stepSize,
          };
          gridRect = {
            x1: -gridOffset.x,
            y1: -gridOffset.y,
            x2: unScale(width) - gridOffset.x + stepSize,
            y2: unScale(height) - gridOffset.y + stepSize
          };
          gridFullRect = {
            x1: Math.min(stageRect.x1, gridRect.x1),
            y1: Math.min(stageRect.y1, gridRect.y1),
            x2: Math.max(stageRect.x2, gridRect.x2),
            y2: Math.max(stageRect.y2, gridRect.y2)          
          };
        
        let solutionName = $('input[name=solutionNo]:checked').val();

        switch (solutionName){
          case "solution1":
            drawLinesSolution1();
            break;
          case "solution2":
            drawLinesSolution2();
            break;
          case "solution3":
            drawLinesSolution3();
            break;            
          case "solution4":
            drawLinesSolution4();
            break;            
        }
        
      }
      

      function unScale(val){
        return (val / stage.scaleX());
      }

      
      
      /* Solution 1 draws the grid on the stage
      * This is the most simple approach. Zoom-in works fine,
      * but when we zoom out we get blank areas around the stage.
      * This is because we rely on the Stage.width() & .height() which 
      * are only relevant when we define the stage.
      */
      function drawLinesSolution1(){      

        const xSize= stage.width(), 
              ySize= stage.height(),
              xSteps = Math.round(xSize/ stepSize), 
              ySteps = Math.round(ySize / stepSize);

        // draw vertical lines
        for (let i = 0; i <= xSteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: i * stepSize,
              points: [0, 0, 0, ySize],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })
          );
        }
        //draw Horizontal lines
        for (let i = 0; i <= ySteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              y: i * stepSize,
              points: [0, 0, xSize, 0],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })
          );
        }
        
        // Draw a border around the viewport
       this.gridLayer.add(
         new Konva.Rect({
           x: viewRect.x1 + 2,
           y: viewRect.y1 + 2,
           width: viewRect.x2 - viewRect.x1 - 4,
           height: viewRect.y2 - viewRect.y1 - 4,
           strokeWidth: 4,
           stroke: 'red'           
         }))
        
        this.gridLayer.batchDraw();
        
      }

      /* Solution 2 draws the grid on the merged stage & viewport space
      * This is better because when we zoom in we draw the grid on the 
      * space around the stage.
      *
      */
      function drawLinesSolution2(){

        const 
          // find the x & y size of the grid
          xSize = (fullRect.x2 - fullRect.x1),
          ySize = (fullRect.y2 - fullRect.y1), 
            
          // compute the number of steps required on each axis.
          xSteps = Math.round(xSize/ stepSize), 
          ySteps = Math.round(ySize / stepSize);

        // draw vertical lines
        for (let i = 0; i <= xSteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: fullRect.x1 + i * stepSize,
              y: fullRect.y1,
              points: [0, 0, 0, ySize],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })               
          );
        }
        //draw Horizontal lines
        for (let i = 0; i <= ySteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: fullRect.x1,
              y: fullRect.y1 + i * stepSize,
              points: [0, 0, xSize, 0],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })
          );
        }

        // Draw a border around the viewport
       this.gridLayer.add(
         new Konva.Rect({
           x: viewRect.x1 + 2,
           y: viewRect.y1 + 2,
           width: viewRect.x2 - viewRect.x1 - 4,
           height: viewRect.y2 - viewRect.y1 - 4,
           strokeWidth: 4,
           stroke: 'red'           
         }))
        
        this.gridLayer.batchDraw();        
      }


      /* Solution 3 is the same as solution 2 with a fix for the dancing grid effect.
      */
      function drawLinesSolution3(){

        let fullRect = gridFullRect;
        const 
          // find the x & y size of the grid
          xSize = (fullRect.x2 - fullRect.x1),
          ySize = (fullRect.y2 - fullRect.y1), 
            
          // compute the number of steps required on each axis.
          xSteps = Math.round(xSize/ stepSize), 
          ySteps = Math.round(ySize / stepSize);

        // draw vertical lines
        for (let i = 0; i <= xSteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: fullRect.x1 + i * stepSize,
              y: fullRect.y1,
              points: [0, 0, 0, ySize],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })               
          );
        }
        //draw Horizontal lines
        for (let i = 0; i <= ySteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: fullRect.x1,
              y: fullRect.y1 + i * stepSize,
              points: [0, 0, xSize, 0],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })
          );
        }

        // Draw a border around the viewport
       this.gridLayer.add(
         new Konva.Rect({
           x: viewRect.x1 + 2,
           y: viewRect.y1 + 2,
           width: viewRect.x2 - viewRect.x1 - 4,
           height: viewRect.y2 - viewRect.y1 - 4,
           strokeWidth: 4,
           stroke: 'red'           
         }))
        
        this.gridLayer.batchDraw();        
      }
      

      /* Solution 4 is the same as solutions 2 & 3 with a clipping area defined.
      */
      function drawLinesSolution4(){
  
        // set clip function to stop leaking lines into non-viewable space.
        gridLayer.clip({
          x: viewRect.x1,
          y: viewRect.y1,
          width: viewRect.x2 - viewRect.x1,
          height: viewRect.y2 - viewRect.y1
        });        
  
        let fullRect = gridFullRect;
        
        const 
          // find the x & y size of the grid
          xSize = (fullRect.x2 - fullRect.x1),
          ySize = (fullRect.y2 - fullRect.y1), 
            
          // compute the number of steps required on each axis.
          xSteps = Math.round(xSize/ stepSize), 
          ySteps = Math.round(ySize / stepSize);

        // draw vertical lines
        for (let i = 0; i <= xSteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: fullRect.x1 + i * stepSize,
              y: fullRect.y1,
              points: [0, 0, 0, ySize],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })               
          );
        }
        //draw Horizontal lines
        for (let i = 0; i <= ySteps; i++) {
          this.gridLayer.add(
            new Konva.Line({
              x: fullRect.x1,
              y: fullRect.y1 + i * stepSize,
              points: [0, 0, xSize, 0],
              stroke: 'rgba(0, 0, 0, 0.2)',
              strokeWidth: 1,
            })
          );
        }

        // Draw a border around the viewport
       this.gridLayer.add(
         new Konva.Rect({
           x: viewRect.x1 + 2,
           y: viewRect.y1 + 2,
           width: viewRect.x2 - viewRect.x1 - 4,
           height: viewRect.y2 - viewRect.y1 - 4,
           strokeWidth: 4,
           stroke: 'red'           
         }))
        
        this.gridLayer.batchDraw();        
      }


      
      drawLines();
      stage.add(layer);

      var rStageBorder = new Konva.Rect({
        x: 2,
        y: 2,
        width: width - 4,
        height: height - 4,
        strokeWidth: 4,
        stroke: 'blue',        
      });
      var rStageFill = new Konva.Rect({
        x: 2,
        y: 2,
        width: width - 4,
        height: height - 4,
        fill: 'blue',
        opacity: 0.2
      });
      
      layer.add(rStageFill, rStageBorder); 
      
      var r1 = new Konva.Rect({
        x: 0,
        y: 0,
        width: 40,
        height: 40,
        fill: 'blue',
        draggable: true,
      });
      layer.add(r1);

      var circle = new Konva.Circle({
        x:  stage.width() / 2,
        y: stage.height() / 2,
        radius: 50,
        fill: 'blue',
        draggable: true,
      });
      layer.add(circle);
      let x = new Konva.Layer();
      var scaleBy = 1.01;
      let currentScale = 6;
      let scales = [5,4,3,2.5,2,1.5,1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.05]
      stage.on('wheel', (e) => {
        // stop default scrolling
        e.evt.preventDefault();

        var oldScale = stage.scaleX();
        var pointer = stage.getPointerPosition();
        
        var mousePointTo = {
          x: (pointer.x - stage.x()) / oldScale,
          y: (pointer.y - stage.y()) / oldScale,
        };

        // how to scale? Zoom in? Or zoom out?
        let direction = e.evt.deltaY > 0 ? 1 : -1;

        // when we zoom on trackpad, e.evt.ctrlKey is true
        // in that case lets revert direction
        if (e.evt.ctrlKey) {
          direction = -direction;
        }

        if (direction > 0){
          currentScale = currentScale > 0 ? currentScale - 1 : currentScale;
        }
        else {
          currentScale = currentScale < scales.length - 1 ? currentScale + 1 : currentScale;
        }
        
        newScale = scales[currentScale];

        stage.scale({ x: newScale, y: newScale });

        var newPos = {
          x: pointer.x - mousePointTo.x * newScale,
          y: pointer.y - mousePointTo.y * newScale,
        };

        stage.position(newPos);

        
        $('#scaleDisplay').html(stage.scaleX());
        
        
        stage.draw();
        drawLines();
      });
      
      $('#saveDefault').on('click', function(){
          var dataURL = stage.toDataURL( );
          downloadURI(dataURL, 'stage.png');
        })


      $('#saveExtended').on('click', function(){
          var dataURL = stage.toDataURL({x: -200, y: -200, width: 1200, height: 800});
          downloadURI(dataURL, 'stage.png');
        })
      
      // function from https://stackoverflow.com/a/15832662/512042
      function downloadURI(uri, name) {
        var link = document.createElement('a');
        link.download = name;
        link.href = uri;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        delete link;
      }


    stage.on('dragend', function () {
        drawLines();
      });
      
      
              
            
!
999px

Console