Pen Settings

JavaScript

Babel includes JSX processing.

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

Auto Save

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.

Flutter

              
                import 'dart:async';
import 'dart:math';
//import 'dart:ui';
import 'dart:ui' as ui;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

///
/// gradients
///
void main() {
  runApp(MaterialApp(
    home: Scaffold(
        body: Container(
          child: Board(),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [Color(0xff444444), Color(0xff1a1a1a)],
            ),
          ),
        ),
        backgroundColor: backgroundColor),
    debugShowCheckedModeBanner: false,
  ));
}

final size = ui.window.physicalSize / ui.window.devicePixelRatio;

const maxPoints = 19;

const force = Offset(0, 1);

const acceleration = 1.05;

const backgroundColor = Color.fromARGB(255, 67, 67, 67);

const fillColor0 = Color.fromARGB(255, 251, 39, 148);

const fillColor1 = Colors.white;

const fillColors = [fillColor1, fillColor1, fillColor1, fillColor0];

const strokeColors = [fillColor1, fillColor1, fillColor1, fillColor0];

const fillRed = Color(0xffff0000);

final segmentMaxWidth = size.height / 12;

const segmentMinWidth = 2.0;

final segmentMaxLength = size.height / 3;

final random = Random();

const maxNumLines = 7;

const lightnessFactor = 0.95;

const darkerFactor = 0.25;

const globalOpacity = 1.0;

extension on Color {
  HSLColor get hsl => HSLColor.fromColor(this);

  double get lightness => hsl.lightness;

  Color withLightness(double value) => hsl.withLightness(value).toColor();

  Color darker(double factor) {
    final hslColor = HSLColor.fromColor(this);
    return hslColor
        .withLightness(max(0, hslColor.lightness * (1 - factor)))
        .toColor();
  }

  Color lighter(double factor) {
    final hslColor = HSLColor.fromColor(this);
    return hslColor
        .withLightness(min(1, hslColor.lightness * (1 + factor)))
        .toColor();
  }
}

class Point {
  final Offset offset;
  final Offset force;

  final bool active;

  static const zero = Point(Offset.zero, Offset.zero, false);

  const Point(this.offset, this.force, [this.active = true]);

  Point update() => active
      ? Point(offset + force, force * acceleration, offset.dy < size.height)
      : zero;

  Offset up(double value) => offset + Offset(0, -value);

  Offset down(double value) => offset + Offset(0, value);

  Point freeze() => Point(offset, Offset.zero, false);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Point &&
          runtimeType == other.runtimeType &&
          offset == other.offset &&
          force == other.force &&
          active == other.active;

  @override
  int get hashCode => offset.hashCode ^ force.hashCode ^ active.hashCode;
}

class Segment {
  final Point point1;

  final Point point2;

  final Color strokeColor;

  final Color fillColor;

  Offset get offset1 => point1.offset;

  Offset get offset2 => point2.offset;

  final Segment previous;

  const Segment(
    this.point1,
    this.point2, {
    @required this.previous,
    this.strokeColor,
    this.fillColor,
  });

  bool get active => point1.active && point2.active;

  List<Offset> get corners {
    final previousWidth =
        previous != null ? previous.segmentWidth : segmentWidth;
    final width = segmentWidth;
    return [
      point1.up(previousWidth),
      point2.up(width),
      point2.down(width),
      point1.down(previousWidth),
    ];
  }

  double get segmentWidth => max(
        segmentMinWidth,
        segmentMaxWidth -
            (Rect.fromPoints(point1.offset, point2.offset).longestSide /
                    segmentMaxLength) *
                (segmentMaxWidth - segmentMinWidth),
      );

  Segment update() {
    final newFillColor = fillColor
        .withLightness(max(0.05, fillColor.lightness * lightnessFactor));
    print('Segment.update... $newFillColor');
    return Segment(
      point1.update(),
      point2.update(),
      previous: previous,
      strokeColor: strokeColor,
      fillColor: newFillColor,
    );
  }

  Segment freeze() => Segment(
        point1.freeze(),
        point2.freeze(),
        previous: previous,
        strokeColor: strokeColor,
        fillColor: fillColor,
      );
}

class Board extends StatefulWidget {
  @override
  _BoardState createState() => _BoardState();
}

class _BoardState extends State<Board> with SingleTickerProviderStateMixin {
  List<Segment> _segments = [];
  StreamController<List<Segment>> _streamer;
  Stream<List<Segment>> get _segment$ => _streamer.stream;

  final List<List<Segment>> _freezedLines = [];
  StreamController<List<List<Segment>>> _freezedStreamer;
  Stream<List<List<Segment>>> get freezedShape$ => _freezedStreamer.stream;

  Offset cursor;

  AnimationController _anim;

  Timer timer;

  @override
  void initState() {
    cursor = size.bottomRight(Offset.zero) * random.nextDouble();

    _streamer = StreamController<List<Segment>>()..add(<Segment>[]);
    _freezedStreamer = StreamController<List<List<Segment>>>()..add([]);

    timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      final freezables = _segments
          .where((element) => element.active)
          .map((element) => element.freeze())
          .toList();
      _segments.clear();
      _freezedLines.add([...freezables]);
      _freezedStreamer.add(_freezedLines);
      if (_freezedLines.length == maxNumLines) {
        _anim.reset();
        timer.cancel();
      }
    });

    _anim = AnimationController.unbounded(
        vsync: this, duration: Duration(seconds: 1))
      ..repeat()
      ..addListener(_onTick);
    super.initState();
  }

  void _onTick() {
    _moveCursor();
    _updateSegments();
  }

  void _moveCursor() {
    double nextX = (random.nextDouble() * segmentMaxLength * 2) -
        segmentMaxLength /** 1.5 / 2*/;
    if ((cursor.dx + nextX > size.width) || (cursor.dx + nextX < 0))
      nextX = nextX * -1;

    double nextY =
        (random.nextDouble() * segmentMaxLength) - segmentMaxLength / 2;
    if (cursor.dy + nextY > size.height || cursor.dy + nextY < 0)
      nextY = nextY * -1;

    cursor = cursor + Offset(nextX, nextY);
    if (_freezedLines.length < maxNumLines) _addSegment(cursor);
  }

  @override
  Widget build(BuildContext context) => Stack(
        children: [
          RepaintBoundary(
            child: StreamBuilder<List<List<Segment>>>(
              stream: freezedShape$,
              builder: (context, snapshot) => CustomPaint(
                size: size,
                painter: BackgroundPainter(snapshot.data ?? []),
              ),
            ),
          ),
          StreamBuilder<List<Segment>>(
            initialData: <Segment>[],
            stream: _segment$,
            builder: (_, stream) => CustomPaint(
                size: size, painter: ForegroundPainter(stream.data)),
          ),
        ],
      );

  void _addSegment(Offset offset) {
    _segments
      ..add(
        Segment(
          _segments.isEmpty ? Point(offset, force) : _segments.last.point2,
          Point(offset, force),
          previous: _segments.isNotEmpty ? _segments.last : null,
          strokeColor: strokeColors[_freezedLines.length % strokeColors.length],
          fillColor: fillColors[_freezedLines.length % fillColors.length],
        ),
      );
  }

  void _updateSegments() {
    _segments = _segments
        .skip(max(0, _segments.length - maxPoints))
        .where((element) => element.active)
        .map((element) => element.update())
        .toList();
    _streamer.add(_segments);
  }
}

class BackgroundPainter extends CustomPainter {
  final List<List<Segment>> lines;

  BackgroundPainter(this.lines);

  @override
  void paint(Canvas canvas, Size size) {
    for (final segments in lines) {
      for (final segment in segments) drawSegment(canvas, segment);
    }
  }

  @override
  bool shouldRepaint(BackgroundPainter oldDelegate) => true;
}

class ForegroundPainter extends CustomPainter {
  static final fill = Paint()..color = fillColors.first;
  static final stroke = Paint()
    ..color = Colors.grey
    ..style = PaintingStyle.stroke;

  final List<Segment> segments;

  const ForegroundPainter(this.segments);

  @override
  void paint(Canvas canvas, Size size) {
    if (segments.isEmpty) return;
    for (final segment in segments.where((segment) => segment.active))
      drawSegment(canvas, segment);
  }

  @override
  bool shouldRepaint(ForegroundPainter oldDelegate) =>
      segments.isNotEmpty && !listEquals(segments, oldDelegate.segments);
}

void drawSegment(Canvas canvas, Segment segment) {
  final path = Path()
    ..moveTo(segment.corners[0].dx, segment.corners[0].dy)
    ..lineTo(segment.corners[1].dx, segment.corners[1].dy)
    ..lineTo(segment.corners[2].dx, segment.corners[2].dy)
    ..lineTo(segment.corners[3].dx, segment.corners[3].dy)
    ..close();
  canvas.drawPath(
    path,
    Paint()
      ..shader = ui.Gradient.linear(
        segment.corners[0],
        segment.corners[2],
        [
          segment.fillColor.lighter(darkerFactor).withOpacity(globalOpacity),
          segment.fillColor.withOpacity(globalOpacity),
          segment.fillColor.darker(darkerFactor).withOpacity(globalOpacity),
        ],
        [.0, .3, .8],
      ),
  );
}

              
            
!
999px

Console