0

Is it possible to draw lines/shapes (see example) within a :before pseudo-element? I was thinking about the canvas uses in CSS, but after some research, I came to the conclusion that canvas within pseudo elements is just not possible. Is there another way?

Example of the lines

m4n0
  • 29,823
  • 27
  • 76
  • 89
Sbaliyev
  • 163
  • 7

2 Answers2

0

I solved the problem by creating a canva element at the beginning of my div and giving it the same properties as the ::before would have, so I could draw on it and stretch the width and height of the canva to 100% through the css. Here's the code(I used 2000 width and height on canva element to not result in a drawing with low resolution):

Put this inside the div:

<canvas id="myCanvas" width="2000" height="2000">
        <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");
        
        // Create gradient
        var grd = ctx.createLinearGradient(0, 2000, 2000, 0);
        grd.addColorStop(0, "#121214");
        grd.addColorStop(1, "#580082");
        ctx.fillStyle = grd;
        
        // Path
        ctx.beginPath()
        ctx.lineWidth = "1";
        ctx.moveTo(0, 0);
        ctx.lineTo(2000, 0);
        ctx.lineTo(2000, 1920);
        ctx.lineTo(1000, 1998);
        ctx.lineTo(0, 1920);
        ctx.lineTo(0, 0);
        ctx.fill()
        </script>
    </canvas>

then, the css:

canvas {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 120%;
      z-index: -1;
  }

The result was this beautiful background with purple gradient and V shape that saved me 1.2MB compared to the PNG i was using:

enter image description here

xandekoch
  • 11
  • 1
0

You can't use <canvas> in the pseudo element, but you can use an SVG. See this answer: https://stackoverflow.com/a/19255455/7172604

Stuart Nichols
  • 1,026
  • 1
  • 8
  • 11