## 使用画布绘制一个流动管道_使用画布绘制和动画化果冻形状

In recent times, we have seen that the web is no longer a page in a browser full of squares. Every day there are more designs which incorporate irregular shapes.

In this tutorial we want to teach you how to create and animate shapes with a jelly effect. At the end, you will be able to create the jelly shape you want, and animate it according to your needs without too much effort.

Specifically, in this first part we will see how to achieve the following result:

## 介绍(Introduction)

The maths behind an effect like this can be very difficult to achieve. That's why we have tried to group the code needed to create and animate jelly shapes in a library that is easy to use for developers.

At the same time, we have been inspired by this pen by Thom Chiovoloni, inspired as well in the game The Floor is Jelly. And we have started specifically from this implementation of the jelly physics.

So, we've packaged this implementation into a library we've just called jelly.js, to which we've added everything we need to get jelly shapes easily. Then let's see how to use it!

## 使用SVG路径创建形状(Creating the shapes with SVG paths)

We have chosen SVG paths to create the shapes, because we believe it is the easiest and most customizable way we have to do it. In this way, we can create the shapes that we want in a vector editor (like Inkscape or Illustrator), and insert them directly into our HTML document, or even import them from JavaScript.

For example, we can draw a simple shape like this:

Then we can include the relevant SVG code directly in the HTML:

<!-- SVG with a pentagon path -->
<!-- Note the display: none style, because we don't want to show the SVG, but just get the path from JavaScript -->
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="400" height="400" style="display: none">
<path id="pentagon-path" d="m200 97.218 108.07 78.524-41.28 127.04h-133.58l-41.281-127.04z"/>
</svg>

## 设置标记(Setup the markup)

We also need a canvas to draw the shape, and some other elements with the aim of moving a letter (S, from Scotch) coordinately with the centroid (average point) of the shape.

<div class="jelly-container">
<!-- Canvas to draw the jelly pentagon -->
<canvas class="jelly-canvas"></canvas>

<!-- Text in the centroid of the jelly pentagon -->
<div class="centroid-container">
<div class="centroid-text">S</div>
</div>
</div>

## 有点风格(A bit of style)

For this example we need very few styles. Let's see the code:

/* General styles */

html, body {
margin: 0;
}

body {
background-color: #D98327;
overflow: hidden;
}

/* Jelly styles */

.jelly-container {
position: relative;
display: inline-block;
left: 50%;
margin-left: -200px;
}

.jelly-container, .jelly-canvas {
width: 400px;
height: 400px;
}

/* It's important to position the .centroid-container in the top-left corner
This way the .centroid-text will be positioned in the center (with JavaScript) */
.centroid-container {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
pointer-events: none;
}

.centroid-text {
font-size: 100px;
color: white;
}

## 做成果冻(Making it jelly)

Finally we have arrived at the most fun part! Let's draw our pentagon on the canvas and see how we can animate it in a jelly way. But don't worry, it will be very easy using our library.

We just need a few lines of code to draw our pentagon, and to get it reacting in a jelly way if we move the mouse to the edges of the shape:

/* Setup options */

var options = {
paths: '#pentagon-path',     // Shape we want to draw
pointsNumber: 10,            // Number of points
maxDistance: 70,             // Max distance among points
color: '#5C1523',
centroid: '.centroid-text'   // Element to move accordingly with the centroid of the shape
// debug: true               // Uncomment this to see the points
};

/* Initializing jelly */

var jelly = new Jelly('.jelly-canvas', options);

Note that the constructor of our library (Jelly) receives a canvas element and a set of options. We can also provide an array of options, a set of options for each shape we want to draw. For a detailed description of the available options, you can check the Github repository.

We could leave it there, but our library has much more to offer. So let's look at some other things we can do.

## 实施果冻拖动(Implementing a jelly dragging)

To illustrate a little more the options we have (and for fun), let's see how we can shake our pentagon as we drag it across the screen.

First, we need to know when the mouse is inside the shape, to allow dragging it only when that happens. Check the following code, doing just that:

/* Check hover item (shape) and update cursor */

var container = document.querySelector('.jelly-container');
var hoverIndex = -1;

function checkHover() {
// The getHoverIndex function will return the index of the shape being hovered, or -1
hoverIndex = jelly.getHoverIndex();
container.style.cursor = hoverIndex === -1 ? 'default' : 'pointer';
window.requestAnimationFrame(checkHover);
}
window.requestAnimationFrame(checkHover);

And let's see how we can implement a basic dragging logic. Please look at the comments to understand what is happening there, and pay special attention to the shake function:

/* Drag and drop */

var startX, startY, dx, dy, endX = 0, endY = 0, x = 0, y = 0, lastX = 0, lastY = 0;
var down = false;
// This will be the max distance for shaking
var shakeLimit = 5;

if (hoverIndex >= 0) {
startX = e.clientX;
startY = e.clientY;
down = true;
}
});

if (down) {
x = e.clientX - startX;
y = e.clientY - startY;
container.style.transform = 'translate(' + (endX + x) + 'px, ' + (endY + y) + 'px)';

dx = x - lastX;
dy = y - lastY;
if (dx > shakeLimit || dx < - shakeLimit) dx = dx < 0 ? - shakeLimit : shakeLimit;
if (dy > shakeLimit || dy < - shakeLimit) dy = dy < 0 ? - shakeLimit : shakeLimit;

// The shake function will "move" the half of the points (alternately) the distance defined
jelly.shake({x: - dx, y: - dy});

lastX = x;
lastY = y;
}
});

function mouseUp() {
if (down) {
down = false;
endX += x;
endY += y;
}
}

if (e.target.nodeName == 'HTML') {
mouseUp();
}
});

## 性能和浏览器支持(Performance and browser support)

The browser support is really good, because all modern browsers have support for canvas. But jelly.js uses Promises, so we need a polyfill for any browser that does not support native promises.

On the other hand, the performance is very variable according to the browsers and the operating systems. This is due to the CPU intensive work in each animation frame. So, don't abuse the use of these effects, because they can kill website performance.

## 结论(Conclusion)

And we are done! So far we have created a truly jelly pentagon without too much effort. Our shape also change the cursor on hover event, and respond to dragging in a jelly way as well :)

You can see the final demo here, and you can get the full code on Github too.

These are not the only things we can do. In fact, in the second part of this tutorial we will build an awesome slider, where everything will be jelly. In broad outline, we will learn how to:

• Draw more jelly shapes, and text!

画更多的果冻形状和文字！
• Use images inside the shapes, not only solid colors.

在形状内部使用图像，不仅要使用纯色。
• Animate the shapes to show or hide them smoothly.

对形状进行动画处理以平滑显示或隐藏它们。
• Morph from a jelly shape to another.

从果冻形状变形为另一个形状。
• Make the entire slider responsive.

使整个滑块响应。

We really hope you enjoyed it and found it useful! See you in the second part ;)

### AtCoder Beginner Contest 174 E.Logs

AtCoder Beginner Contest 174 E.Logs 题目链接 到最后才发现是二分，菜菜的我/(ㄒoㄒ)/~~ 我们直接二分 [1,max{a[i]}][1,max\lbrace a[i]\rbrace][1,max{a[i]}] 即可，对每一个 midmidmid，每个数 a[i]a[i]a[i] 只需要切 a[i]−1mid\frac{a[i]-1}{mid}mi...

### VMware centOS7 下通过minikube部署Kubernetes

1、环境准备： VMware CentOS-7-x86_64 CPU：2*2core 内存：8G 宿主机和虚拟机需网络互通，虚拟机外网访问正常 Centos发行版版本查看：cat /etc/centos-release root用户操作 2、禁用swap分区 Kubernetes 1.8开始要求关闭系统的Swap，可暂时关闭或永久禁用， 使用 $free -m 确认swap是否为开启状态$ s...

### 指针OR数组？用他们来表达字符串又有何不同？

cocowy的编程之旅 在学习C语言的过程中我们经常可以看到或者听到这样一句话：数组其实等价于指针，例如： 在这里可以轻松的看出输出后他们的值相等，其实在计算机内存里面，p为本地变量，有着他自己的作用域。而指针变量q保存着这个数组的首地址,通过*号指向这个地址保存的变量值。 然而我们再看一个例子： 这个时候计算机报错，这是为什么呢？ 其实原因很简单，指针说指向的这个字符串的地址是位于计算机代码段地...

### NIO Socket 编程实现tcp通信入门（二）

1、NIO简介 NIO面向通道和缓冲区进行工作，数据总是从通道读取到缓冲区中，或者从缓冲区写入到通道中。可以双向传输数据，是同步非阻塞式IO。NIO还引入了选择器机制，从而实现了一个选择器监听多个底层通道，减少了线程并发数。用NIO实现socket的Tcp通信需要掌握下面三个知识点： Buffer 缓冲区 Channel 通道 Selector 选择器   2、java.nio.Buff...

### [字节码系列]ObjectWeb ASM构建Method Monitor

在前面的篇章中，我们看到Java Instrutment的强大能力，本篇，我们将介绍如何使用ObjectWeb ASM的字节码增强能力构建Method Monitor       1．什么是ObjectWeb ASM      ObjectWeb ...