让天下没有难学的编程 |

全部资讯


SVG Sprites

SVG sprites Introduction Image sprites (even in the lowly bitmap format) can save a huge amount of time, and more importantly a whole bunch of annoying individually loaded resources. As cool as that all is, it certainly becomes a little bit less magical anytime you need to create separate sprites for retina screens. If that isn’t enough, a media query for each? Holy no. But this post isn’t just a trip down memory lane, it’s a celebration of that all being in the past. Today, we’ll review some approach options, and implement a scaleable svg sprite design/development process that could minimally save you a ton of money on your car insurance. The Basic’s If coming from a bitmap sprite world, you’re expecting your image to be your sprite. Well, it is but this one opens in your favorite text editor. The basic structure of a svg sprite image: <svg version="1.1" xmlns="http://www.w3.org/2000/svg"> <defs> <symbol id="caret" viewBox="0 0 16 16"> <polygon points="3,5 8,11 13,5" /> </symbol> </defs> </svg> For each icon in this sprite a <symbol> should be added (as children to <defs>) with a viewBox and an id attribute. This sprite can be it's own file, or it can be placed right at the top of the page it's used on. If used on the page, you'll ned to hide the sprite from rendering with a display:none or something similar. SVG Sprite Considerations There are a few important points to think through when using svg's in general and the same goes for an svg sprite. The approach you take to building your sprite may depend upon some of the considerations below. Things to consider: Support Svg sprites with an external source won’t work in IE 9, 10, 11 without a polyfill. See SVG for Everybody. Native apps still appear to prefer bitmap images. The Domain Sprite images need to be served from the same domain that’s serving the actual page in order to work. If this isn’t possible you still have a couple (less desirable) options. Use the svg’s inline Add the sprite to the page/component(s) it’s used on Individual <img> tag's for every icon Both of these approaches are going to create more markup that needs to be rendered every time the page loads. This may or may not affect your page’s loading time a bit more than loading a single sprite image once (with an external image). Icon Sizing Keeping icon and viewBox sizes consistent for each icon is going to save you a lot of time, especially with sprites. If you aren’t familiar with these attributes already you can read up on them in this article: How to Scale SVG Color Manipulation Manipulating svg's with CSS is one of my favorite features. Being able to do this means we can change the color on :hover, or we can reuse the same icon in different places with different colors, sizing, or rotation without worrying about pixelation. There are only two ways to manipulate svg’s with CSS currently: Note: svg's referenced with <img> tag's are untouchable. Add the entire svg sprite to the page, or reference an external image Can manipulate fill (or stroke) of any shape that doesn’t have a fixed fill (or stroke). Cannot make fill (or stroke) colors different for only some shapes in a single icon unless they are fixed. Drop each stinkin’ svg icon right on the page where it's needed Can manipulate shapes as long as they can be selected (by the element, class, or id) Can manipulate color of individual elements Can manipulate fill or stroke of any shape that doesn’t have a fixed fill or stroke. Note: Adding a sprite or svg directly to a page can/probably will make it a bit harder to maintain your icons. Putting your sprites into action Sprite image setup Since we can’t manipulate colors for shapes that have fills or strokes on them, we’re going to remove them for every shape or group that we want to change. This is a good time to remove any junk comments, or empty <g> (group) tag’s if they exist. Just be sure you know what you’re removing! Before removal: <symbol id="caret-down" viewBox="0 0 16 16" > <polygon points="3,5 8,11 13,5" fill=”#333333” /> </symbol> After removal: <symbol id="caret-down" viewBox="0 0 16 16" > <polygon points="3,5 8,11 13,5" /> </symbol> Note: if you have an icon with multiple shapes, and you only want to manipulate some you can keep fixed fills (or strokes) on the elements that shouldn’t change. Keep in mind that no matter how much CSS you throw at them, they will not change if they have a fixed color. Consistent icon sizes See an example of mismatched icons below: The Codepen icon is a bit smaller than the Github icon. This isn’t an extreme difference, but if we saw these next to each other, we’d certainly notice it. There are a couple things we can do to make sure they render consistently: First and foremost, try to use icons from the same source to keep them as consistent as possible (Nucleo is amazing). If you can’t do that, throw them all in a Sketch file to be used as a working icon sprite source file. Use separate art boards or symbols for each icon and turn on the grid or create rulers to line them up and resize them. Export individually in the .svg format and copy and paste them into your sprite. Note: most design tools will load the file with comments, and junk code. Sketch is no different, but luckily, the grouping does match the grouping of the elements in your artboard pretty closely. Manipulating sprite icon colors with CSS Now that we’ve removed the fill or stroke the icon’s defined shapes will be black by default. Gross, black doesn’t exist in the real world, plus chances are that’s not what you’re going for anyway. Setting a specific color: .my-icon { fill: rebeccapurple } Setting a dynamic color: .my-icon { fill: currentColor } The currentColor value is the inherited color value (from it’s parents). This is great for auto-magically changing icon colors without writing extra CSS. Note: Despite possibly being the only value that uses camel-case, currentColor is a plain old CSS. It can be used with other properties that use color values. Read more about currentColor on CSS-Tricks. I find it helpful to create two utility classes for my icons sprites. .icon-fill for icons that have fill’s I’d like to manipulate, and .icon-stroke for the stroke-based icons. .icon-fill { fill: currentColor } .icon-stroke { stroke: currentColor } Applying this class to my icon references ensures that I never have to worry about the icon not matching the text color, which easily covers 90% of the use cases. Adding icons to your page Basic SVG reference in markup <svg class="icon-fill"> <use xlink:href="img/sprite_base.svg#caret-down"></use> </svg> If the image exists on the page your referencing them on you can omit the file path and just use #iconName Break a leg We hope you never bitmap unless you need to again! Check out a sample of the code: 收起
显示全部文字 查看全文
作者/Tony Montemorano
时间/2018-02-08 19:16:32

Creating Tesla's Website With Bootstrap 4

We explore some of the new Bootstrap 4 features by building a copy of Tesla's Roadster web page.
查看全文
作者/Danny Markov
时间/2018-02-08 00:02:31

Using Bash Functions To Start A Local Environment Quicker

I can never remember what command(s) to type in Terminal to start my local development environments. Even after a few months on a project, I'm always going back to my documentation after every reboot or update. It's definitely a #firstworldproblem but there has to be a better way than a Google doc and copy/paste. There is. Let's write some bash functions. Open your terminal and type the following to get into your .bash_profile so we can write a function or two: nano ~/.bash_profile Here's a simple example. When I'm working on my company's website, Modea.com, I need to cd into the project repo and then run rails server. This is how I'd do it with one function instead. We're going to create a function named modeaServer and then put each command on its own line. For this basic example, we won't need any parameters. modeaServer () { cd ~/Repos/Modea.com-3.0/ rails server } Once you're happy with what's in your bash_profile, type ^X to save your file and then run the following to load your new changes. source ~/.bash_profile Now whenever I want to start my local instance of Modea.com, I just type "modeaServer" into Terminal and I'll be good to go. What about a more complex example with a parameter? foo() { echo "Parameter #1 is $1" } If I typed "foo bar" into my terminal, I'd get back "Parameter #1 is bar". If I needed a second parameter, I'd write $2 inside my function. You could use parameters in a number of different ways. If you have a number of different sites that are started the same way, you could write one function and make the parameter the directory. start () { cd ~/Repos/$1/ rails server } In this example, you would type start and then the name of your directory. "start site1" would run rails server inside the site1 directory. Side note: .bash_profile isn't the only place you can store these functions. You could also use .bashrc instead depending on your particular needs. While .bash_profile is executed for login shells, .bashrc is executed for interactive non-login shells. I've been a big fan of Panic's Coda 2 for most of my development work. One of the reasons why is that I can have terminal open as a tab along with the rest of my other files. I need to store my functions in .bash_profile for Coda to be able read them. Otherwise, I could use .bashrc instead. Here's an example of typing modeaServer to boot my local environment inside of Coda 2. This obviously is just scratching the surface of what you could do with these functions. You can do a lot more with them than just starting local environments. But if you juggle multiple projects, do yourself a favor and spend 10 minutes setting some functions up!收起
显示全部文字 查看全文
作者/Colin Lord
时间/2018-02-07 14:18:13

How to map user according to his IP and Country, useful for pricing and products based upon global customer-base #DograsWeblog

Article to map/redirect user based on IP/Country: While working on a project, there occured a serious issue. What company need is to show different types of plan rates to different countries and different cost of delivering. Now, we came across how to redirect user based on the country. Going from, sub directories, modal popup and other ways. We then came across a all done work and reference of ip2location. IP2Location™ LITE IP-COUNTRY Database IP2Location™ LITE IP-COUNTRY Database provides a solution to determine the country of origin for any IP address in a few simple steps. First, retrieve the IP address from the networking protocol or server-side variable of the Web server. Next, translate the IP address to an IP number in decimal format to speed up the database query. Lastly, reverse lookup the IP number from the IP2Location™ database to pinpoint the exact geographical location. IP Address Ranges by Country: This page displays the complete IPv4 address ranges organized by country. There are 249 countries listed below, and each link will bring you to a new page containing the respestive IP address ranges. If you are interested to learn more about the ranking of IP addressess allocated for each country, please visit IP Address Reports for details. Since this problem occurred on Drupal too, we have other alternates too. But, the IP2Location work is awesome, thats ready to use. All things deliberately done. Product Features Features: Translates IP address to country. Current Version: February 2018 Database Size: 1.26 MB (81,867 Rows) Database Format: ASCII Text File (Comma Delimited) & Binary (BIN) Refrence for study: https://lite.ip2location.com/database-ip-country https://lite.ip2location.com/ip-address-ranges-by-country https://superbig.co/plugins/country-redirect https://www.drupal.org/project/smart_ip 收起
显示全部文字 查看全文
作者/Nishant Dogra
时间/2018-02-07 05:23:31

#371: ECMAScript 2018 feature set finalized, V8 6.5 and TypeScript 2.7 arrives

This week's JavaScript news — Read this e-mail on the Web JavaScript Weekly Issue 371 — February 2, 2018 The Final Feature Set of ECMAScript 2018 The feature set of ES2018, the next formal version of the underlying language that we eventually call JavaScript, was finalized at the latest TC39 meeting. Here's another code-driven roundup. Dr. Axel Rauschmayer Debugging JavaScript with the New Firefox JS Debugger Firefox’s new JS debugger is pretty powerful, and will help you write fast, bug-free code. Smashing Magazine Understanding Cross-Origin Resource Sharing (CORS) CORS is a mechanism that allows cross-origin HTTP requests (such as using XMLHTTPRequest or the Fetch API) using special server-side HTTP headers. Bartosz Szczeciński Planning a React Application: Whitepaper Start your next React project with confidence. Learn strategies for tooling, frontend and UX, testing and performance to boost your (and your team’s) productivity. Get your free copy. Progress   Sponsor Stimulus 1.0: A JS Framework for HTML You Already Have We linked to the code a few weeks ago but now the CTO of Basecamp and creator of Ruby on Rails shares his vision for an alternative to single-page client-side MVC apps. David Heinemeier Hansson AngularJS's Plan for Stability and Long Term Support AngularJS (yes, not the more modern Angular) will get one more significant release, 1.7, and enter a 3 year LTS period on July 1. Pete Bacon Darwin V8 Release v6.5: Performance Turned Up to 11 Now in beta, the latest V8 (as will be in Chrome 65) supports streaming compilation for WebAssembly and has many array-oriented perf improvements that have a major impact. Mathias Bynens TypeScript 2.7 Released A key release packed with tweaks and new features, if you prefer your JavaScript with optional static types. Microsoft Jobs JavaScript Developer at Econify (New York, NY)We are looking for a React and Node.js developer to work alongside our team on an exciting high profile project. Apply today. econify Front-End Developer/UI DesignerDesign for social impact. We’re seeking a UI Designer to work across ideation, prototyping coding for international development. Catalpa International Looking for a Job at a Company That Prioritizes JavaScript?Try Vettery and we’ll connect you directly with thousands of companies looking for talented front-end devs. Vettery Can't find the right job? Want companies to apply to you? Try Hired.com.-->In Brief How ECMAScript Regular Expressions Are Getting Better news A look at new regex features both in ES2018 and being discussed at TC39 right now.Mathias Bynens Data Visualizations with InfluxDB: Integrating plotly.js tutorial Visualize data with InfluxDB plotly.js, a JavaScript graphing library built on top of d3.js stack.gl.InfluxData  Sponsor Ways to Make Your Code Cleaner and Easier-to-Read with ES6 tutorialSam Williams Optimizing Hash Tables: Hiding The Hash Code tutorial A look at the recent improvements in how V8 v6.3+ stores the keys in hash tables.Sathya Gunasekaran Building a Modal Component with Vue.js tutorialFilipa Lacerda Asynchronous Reduce in JavaScript tutorialSeva Zaikov Airbnb's Extensive JavaScript Style Guide opinion Not new, but continues to get updates and stars a-plenty.Airbnb Why You Should Choose Luxon for Date Wrangling in JavaScript opinionRad Devon 10 Things I Love About Vue opinionDuncan Grant Build a Modern Image Gallery with Vanilla ES6 videoBrad Traversy A Much Faster Way to Debug Code Than with Breakpoints or Console.log Scratchpad/REPL right in your editor, running your code as you type (community edition is free as in beer).Wallaby.js  Sponsor React Scope: Visualize Your React Components Live tools A Chrome extension for visualizing components, state and props.Tiffany Lin React Scope: Visualize Your React Components Live toolsTiffany Lin Glow: Make Flow's Errors Pretty-Printed and Syntax Highlighted toolsJames Kyle Save Time with the Best, Fastest Angular Spreadsheets & UI Components  GrapeCity JavaScript Solutions  Sponsor Sockette: A Tiny WebSocket Wrapper code A 339 byte wrapper around WebSocket that auto reconnects if the connection drops.Luke Edwards xcell: A Libary to Manage Reactive Spreadsheet-Like Calculations code ijk: Transforms Arrays Into Virtual DOM Trees code If you prefer the Lisp approach of data as code..Luke Jackson Curated by Peter Cooper and published by Cooperpress. Like this? You may also enjoy: FrontEnd Focus : Node Weekly : React Status Stop getting JavaScript Weekly : Change email address : Read this issue on the Web © Cooperpress Ltd. Fairfield Enterprise Centre, Lincoln Way, Louth, LN11 0LS, UK 收起
显示全部文字 查看全文
作者/
时间/2018-02-02 00:00:00

A simple BEM convention

Naming with UX in mind The following examples are based on an post I read a while back here. The common BEM convention .Block {} .Block__element {} .Block--modifier {} .Block__element--modifier {} The simplier BEM notation .Block {} .Block-element {} .Block--elementModifier {} .Block-elementName--elementModifier {} Note the camelCase on all element and modifier names. Block names use the UpperCamelCase style. Prefixes for utilities Prefixes for JS hooks .js-Block {} .js-Block--elementModifier {} App prefixes for style utilities to prevent collision with outside styles. .org-Block {} .org-Block-elementName {} .org-Block--elementModifier {} 收起
显示全部文字 查看全文
作者/Kris
时间/2018-02-01 18:32:39

How to Prototype CSS Extensions

Trying to find ways to prototype new CSS features can sometimes be tricky. Some people choose the route of building (or writing plugins for) a CSS preprocessor for experimenting, some people design and parse new custom syntaxes, and still others write 100% JavaScript solutions to demonstrate the features or functionality they are trying to research. For my CSS extension experiments in 2018 I think I've figured out the easiest way to prototype and test things out: Event-driven virtual stylesheets. How to use an event-driven virtual stylesheet Create a <style> tag in DOM, or empty CSS stylesheet in CSSOM Populate that <style> tag or CSSOM stylesheet with a string containing CSS This string can be a JS string, the output of a function, a JS template string, or a combination of these. Manage event listeners (and/or observers) that reprocess the styles when a specific event occurs (on a specific element, if you want) To do step 1, 2, and 4, I can use something like: https://unpkg.com/jsincss/index.js to create and populate a <style> tag based on events. To do step 3 I can write a stylesheet like this, which is a function that holds a JS template string with CSS text inside: https://staticresource.com/element-query-test.js Notice I was able to easily extend this stylesheet by importing a helper function called 'jsincss-element-query' that provides some simple tests for using element queries: https://unpkg.com/jsincss-element-query/index.js Using this kind of setup it's very simple to extend CSS using vanilla JavaScript plugins, and by splitting the 'stylesheet-populating, event-listening' logic from the helper function logic it also helps keep the helper functions very small and quick to prototype! Here's a lightweight element query demo built using these methods: https://staticresource.com/jsincss-element-query-test.html And here's all the setup that was required to get the JavaScript-powered styling working: import jsincss from '//unpkg.com/jsincss/index.js' import stylesheet from './element-query-test.js' import scrollStyles from './element-query-scroll-test.js' jsincss(stylesheet) jsincss(scrollStyles, ['[class*="-scroll-"]'], ['scroll']) import the jsincss function import the main stylesheet function (which itself imports jsincss-element-query) import the scroll styles function (which imports jsincss-element-query) apply the main styles with default options (watching load, resize, input, and click on window) apply the scroll styles with a custom event (watching scroll on all [class*="-scroll-"] elements) 收起
显示全部文字 查看全文
作者/Tommy Hodgins
时间/2018-01-31 08:16:04

10 Free Programming Books You Should Read in 2018

A collection of interesting programming books you should check out in 2018.
查看全文
作者/Georgi Georgiev
时间/2018-01-25 01:23:55

Animated Image Header

I've been thinking a lot lately about what is the nature of a website and what is the design philosophy that we should be taking as web designers and developers. A website is contained but unrestrained. It is built but also two-dimensional. It must be flexible but able to be traversed easily. These sorts of dichotomies are not easy to take in and even more difficult to "get right." It is television, but interactive. It is a poster, but without borders or limits. Design can utilize three dimensions. It is at once a stack of paper and a broadsheet. In the end, the Web is what you make of it. That has been the goal, I suspect, of the W3C. Through the code they have approved and that browsers have implemented, a website can be anything we want it to be. This leaves open a lot of possibilities. One such possibility is like broadcast TV. That's what I was thinking a few days ago while watching an event. I thought, "What about a documentary-style hero image that would slowly move as the user consumes some text information?" So I went out and created it. Here's the finished product: The background image moves very slowly, zooming into the main focus of the image--the bears. The text supports the image and vice versa. Let's take a look at how to set this up. The first snag I ran into was how to get the photo set up with the text over the image. I originally set the photo as a background image with a text overlay. That's simple enough, but I couldn't get the animation onto just the image. I didn't want the entire group of image and text to grow, just the image itself. So I needed to separate all of the elements and stack them using absolute positioning. Here's my final HTML: <header class="hero"> <div class="hero-image"><img class="slow-grow" src="https://unsplash.it/3500?image=1020"/></div> <div class="hero-text"> <h1>Grizzly bears have been reduced in the lower 48 states from an estimated historical population of 50,000 to only about 1,800 today in five small, isolated populations</h1><a class="button" href="#bear-facts">Learn More</a> </div> </header> You can see that inside the header I've included my two elements: the image and the text. Layering them is a matter of adding position: relative to the CSS of the header and then absolutely positioning the hero text and image. I added the z-index values just to make sure the elements stack in the order I want them to go. Here's the CSS: .hero { height: 100vh; overflow: hidden; position: relative; font-family: "Alfa Slab One", cursive; } .hero-text { padding-left: 2rem; position: absolute; top: 1rem; left: 0; width: 35vw; z-index: 50; } .hero-text h1 { text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.2); color: #fff; margin: 0; font-weight: 400; } .hero-image { position: absolute; top: 0; left: 0; z-index: 1; } .hero-image img { width: 100%; margin-top: -25%; -webkit-transform-origin: bottom right; transform-origin: bottom right; } You'll notice that I've added overflow: hidden to the image container. This allows me to grow the image inside of a "frame", so to speak. If you don't have this, the image might bleed into the rest of the text on the site. Now, let's look at animating this image. You could use Javascript, but I prefer using CSS when I can. The animation is instant on download and more performant. CSS animations are pretty easy to work with, but can take some time getting accustomed to the syntax. It's not your normal CSS. For a great overview with examples, check out this series of tutorials on CSS animation from the DevTips YouTube channel. I created a class that I could add the animation to called .slow-grow. Here is the CSS: .slow-grow { -webkit-animation: grow 150000ms ease; animation: grow 150000ms ease; } @-webkit-keyframes grow { 0% { -webkit-transform: scale(1); transform: scale(1); } 100% { -webkit-transform: scale(1.5); transform: scale(1.5); } } @keyframes grow { 0% { -webkit-transform: scale(1); transform: scale(1); } 100% { -webkit-transform: scale(1.5); transform: scale(1.5); } } To create an animation in CSS, you have to first declare the animation through the @keyframes rule. Then you give the animation a name. That name is what you use in the animation property for the class or element that you want to animate. In this example, my animation is named grow and I add that using the animation property on the .slow-grow class. Essentially, the animation makes the image scale up 1.5 times from the beginning of the animation (0%) to the end of the animation (100%). There are some values that I can choose to customize the timing of the animation when I attach it to the class using the animation property. I first need the name of the animation, then how long it should take, then what sort of movement or timing it needs. I chose to use the ease-in-out function but could have easily gone with linear as the value. It would look good, too. The trickier part was the timing. I wanted this to be a super slow growing/zooming action. So I played a lot with the numbers here. There is a balanced relationship between how much the image scales and how fast the animation should be. The less distance it scales, the faster the timing needs to be. The larger the scaling, the slower the timing. Hopefully, that makes sense. You can play around with it and see what I'm talking about. The final part of this entire equation is something powerful and kind of subtle. What direction do you want to scale from? The default is to scale the image up from the middle. The way you decide this is to look at where the text is and where the focus of the image is. I wanted to focus the user on the bears (bottom right) and keep the text at the top left. It made sense to scale the image from the bottom right because that's where I wanted to "zoom in." The point of this technique is to slowly draw the viewer into a particular part of the image. So choose that part of the image and set the the transform-origin to zoom into that area. For this image, it was transform-origin: bottom right;. You can use a wide range of finer measurements to get this just right. Play around with media queries, too, to make sure every device sees what you want them to see. I found that I needed to add this property to the image itself, not the container, since it was the image that I added the .slow-grow class to. Here's the finished product again: It's a nice effect that can be added anywhere that you want to create some subtle movement. This would work really well anytime you're trying to create more emotion on a website. Like it? Hate it? Can it be improved? Leave a comment below. I'd love to hear your thoughts! Feel free to fork this and use it in your own projects. If you think about it, come back and put a link to where you're using it online. I'd love to see this out in the wild!收起
显示全部文字 查看全文
作者/Brian Haferkamp
时间/2018-01-24 05:56:45

Modals are Bad

My journey with modals started with me having an idea for my personal website. The basic idea was to have several buttons on the left side of the screen with text on the right side on the screen. Each button represented a stage of web development. When the button was clicked a modal would open with more text explaining the step. Below is a screenshot of the design. The first step I took was searching for modals on Codepen. I found one that demonstated several different animations associated with opening models. I forked this project and hacked out the code that I needed for the animation I was going to use. I added the buttons I needed and played around with the animation to get what I was going for. Here is what ended up being the final prototype that I was going to use in my project. See the Pen Modal Animations by Gary (@wingsfan70) on CodePen. The operation was as follows. The user clicked on one of the buttons. Each button has a unique ID. The button ID will determine what text gets displayed in the modal window. I used jQuery to provide the functionality of the buttons. I like the design and how it came out. When the modal opens it looks quite nice. All my development was done on my desktop computer. Yes this was bit of an oversight on my part. I thought once I got it looking nice on desktop I would throw some media queries in there and make it look good on mobile. This is were my logic breaks down. I did a couple of Google searches on how to best handle modal windows on mobile. It turns out it is very complicated and a lot more goes into it then just some media queries. So after investing around 12 hours of my time into programming and getting the modal window to look just right I decided to drop the modal design all together. Most of the recommendations from the Google searches said to use either an accordion type design or a slideout in place of the modal. After reviewing several examples on CodePen I decided to go with the slideout method. It fit better in my design then the accordion method. Once again I turned to CodePen for examples of a good slide out. I decided on this one here. I forked this pen and modified it to fit my use case. Fortunately for me I was able to use much of the jQuery that I had already developed in my modal example and just adapt it to work with the slideout. Here is my final result that I will incoporate into my project. See the Pen Custom Slideout Panel by Gary (@wingsfan70) on CodePen. I was very frustrated and disappointed when I learned that it would have been very difficult to make the modal work correctly on mobile. I spent many hours getting it to work and look good on desktop only to have to abandon it. What I learned from this was to do a bit of research prior to jumping in and spending time on a design and then having to scrap the idea because it wouldn't work.收起
显示全部文字 查看全文
作者/Gary
时间/2018-01-22 08:52:26

Simple image Loader

It's important to load images before drawing them on the canvas, otherwise you may run into complication. I'm using this technic when I need to load a bunch of images. we can also add extra variable to them *( like the size of a game sprite for example ) * You can find the final result without any frills here let's start First we need to create an array that will contain all the images we want to load let images_stock = [ { name: "corgi", url: "https://image.ibb.co/k5CmjG/corgi.jpg", // custom variable can be added here }, { name: "puppy",, url: "https://image.ibb.co/etHxrw/puppy.jpg", // custom variable can be added here }, { name: "labrador", url: "https://image.ibb.co/dJZ5db/labrador.jpg", // custom variable can be added here } ]; And we also need to declare two important variables, they will be usefull to know when the loading is complete. let image_loaded = 0, image_to_load = images_stock.length; This variable will contain every images at the end of the loading var images = {}; // and we'll pass through it to draw the images on the canvas like for example // ctx.drawImage(images.puppy.img, 0, 0); // or // ctx.drawImage(images["puppy"].img, 0, 0); The functions The code is pretty straightforward right now we need to declare three frunctions. the first function will assign every images in the "images" object. function processImage() { for (let i = 0; i < image_to_load; i++) { let subject = images_stock[i]; subject.img = loadImage(subject.name, subject.url); images[subject.name] = subject; } } like so ... Object { corgi: {…}, puppy: {…}, labrador: {…} } But will add a new propiety to the object. subject.img = loadImage(subject.name, subject.url); this function will create an Image object with an onLoad event and will return it to the original. function loadImage(name, url) { let img = new Image(); img.onload = () => { console.log(name + " loaded"); load(); }; img.src = url; return img; } When the onload event is complete it will trigger the load() function, I hope the code is pretty self explanatory at this stage function load() { image_loaded += 1; if (image_loaded === image_to_load) { init(); } } This function will compare the number of image we need to load with the number of images we have in total. When all the images are loaded the init() function get triggered and you can finaly use your images in it :) ! 收起
显示全部文字 查看全文
作者/Thibaud Goiffon
时间/2018-01-21 11:25:33

Debugging your front-end like is 2019

(If you are lazy jump to this section to learn what is this article all about.) Remember The Island movie from 2005. I watched it again these days and I realized that the old sci-fi titles start with something really interesting. It is funny how they create a world of flying vehicles and say something like \"The year is 2019 …\". Well, we are 2018 and the public transport is still on the ground. We still can\'t clone people (I hope so) or travel in a giant spaceship which looks like a fully-functional city.收起
显示全部文字 查看全文
作者/
时间/2018-01-20 06:00:00

Debugging your front-end like it's 2019

(If you are lazy jump to this section to learn what is this article all about.) Remember The Island movie from 2005. I watched it again these days and I realized that the old sci-fi titles start with something really interesting. It is funny how they create a world of flying vehicles and say something like \"The year is 2019 …\". Well, we are 2018 and the public transport is still on the ground. We still can\'t clone people (I hope so) or travel in a giant spaceship which looks like a fully-functional city.收起
显示全部文字 查看全文
作者/
时间/2018-01-20 06:00:00

Easing and Brownian Motion

I've had a pen from some time ago featured in the Spark email, which got some likes and views, and made me think that there are others that may be interested in exporing particle motion. I'm going to try to explain the concept of building the particle motion that leads to a natural-looking motion. The basis of this type of motion is what's often referred to as Brownian Motion. Every frame a particle will pick a random point within a square constraint, and move closer to it // update position with vector this.x += (Math.random() * 2 - 1) * this.speed; this.y += (Math.random() * 2 - 1) * this.speed; though the code looks slightly different in this pen, the particles there operate on that principle. The red line shows the direction which the random point was picked, and can be hidden using the showVector setting. Example 1 : move towards random point The problem with this motion is that it looks too rigid, and not at all fluid. To solve this issue, I apply an easing to the vector.. Example 2 : ease towards random point The basis of the easing is vector = vector * a + randomDestination * (1 - a), where a is like an easing amount, as a gets larger the more of the original vector remains the same, and less of the random number gets added ((1 - a)), the changes are smaller. As a gets smaller, the vector uses more of the random point and less of the vector, and the movement gets more erradic. The code now looks like this: // pick random destination this.dx = (Math.random()*2-1) * settings.particleSpeed; this.dy = (Math.random()*2-1) * settings.particleSpeed; // update vector this.vx = this.vx * settings.a + this.dx * (1 - settings.a); this.vy = this.vy * settings.a + this.dy * (1 - settings.a); // update position with vector this.x += this.vx this.y += this.vy You should be able to see a more natural movement emerge with a between 0.9 and 1. This laso depends on speed and frame rate, but I've found that a value close to 0.98 tends to work well. Another variation is to split a; istead of using (1 - a) for the random multipler, to use a separate number (b). This way a + b don't need to add up to 1 Example 3: ease towards random point (with a and b) If the numbers a and b add up to less than 1 (and b is lager than 0), then they'll have a tendency to not travel far, and hover around the same spot, as the cumulative vector is constantly deminishing, and the random component is making shake in it's place. If the combined number (a + b) is larger than 1, they'll have a tendency to travel more because the cumulative vector is growing, and the random component is making the particle change with small increments. So that concludes the basics of how I use use the vector of a particle and a new random position every frame to generate a somewhat fluid motion. With these basics in mind, it's time to do some experiments. Experiment 1 : sine × b I've added a sine wave multiplier to to the b component. If b is larger (positive or negative), it moves faster, if it's closer to 0, then the movement slows down. The relative speed is controlled by b, and how frequently it slows down and speeds up again is controlled using the cycle. Below is the update function code (the initial step is set to random during setup) // incerement step and reset to 0 once it reaches cycle this.step = (this.step + 1) % settings.cycle; // convert step to a number between 0 to 1 const phase = this.step / settings.cycle; // map ramp value to a sine wave value const p1 = Math.sin(phase * 3.14 * 2) // set random destination (unchanged) this.dx = (Math.random()*2-1) * settings.particleSpeed; this.dy = (Math.random()*2-1) * settings.particleSpeed; // update vector (added p1 to b) this.vx = this.vx * settings.a + this.dx * settings.b * p1; this.vy = this.vy * settings.a + this.dy * settings.b * p1; // update position with vector this.x += this.vx this.y += this.vy Experiment 2 : sin & cos on a Instead of multiplying sin × b, I calculate the sine and the cosine, and compute x and y components using sine and cosine; vx uses a × sin and vy uses a × cos. This makes it so that the x and y components move faster and slower in an inverse relation. This creates a little more structured looking result. I've reduced the particle size and reduced the speed of fade to show how this motion ends up looking over time. Other possibilities include maping the speed or other particle values to the amplitude of a frequency range taken from an audio source, like I've done here. Or a much smaller variation on example 2 here. Even with just a few parameters, there's lots to experiment with. Related: In my previous Post, Draw with loops, I show how I use trigonometry to affect change on a particle. 收起
显示全部文字 查看全文
作者/Daniel
时间/2018-01-17 21:50:20

It is easy to Sine wave

Writing a colorful sine wave animation in 34 lines of JS. Seems like people really liked both of my tutorials on how to make a nice animation in a very small amount of JavaScript. Seems like a signal from above that I need to write more of these. This is what we are going to do today: Small little disclaimer over here If you have done a Sine wave animation before, this tutorial won't tell you anything new, other than how to do it in a small amount of JS on a HTML5 Canvas. but if you haven't done any sine wave animations yet, but wanted to, it means that you don't fully understand how Trigonometry or Animations work, at least one of them. So let's review that: How animations work: You draw a particle on a screen. To make it move you have to update the position of the particle and draw it again. How trigonometry works: The Sine is basically a function, that takes an angle as an argument and returns a Y coordinate. Using this information We will draw multiple particles on a screen, each with already familiar for us values: Horizontal position Angle and color. Its not necessary if you want it to be white. Let's get to code. Let's quickly slide through the little setup we have here: <canvas id="C"></canvas> canvas { position: absolute; /*removing the ugly scrollbars */ top: 0; /* by making the body element have the width */ left: 0; /* of 0, because of position: absolute; */ } (()=>{ let $ = c.getContext('2d'), w = c.width = window.innerWidth, h = c.height = window.innerHeight, opts = {}, //object with preferences arr; //we will get to this one in a minute function loop(){ $.fillStyle="#222"; //drawing a black background $.fillRect(0,0,w,h); //as a large full-screen square requestAnimationFrame(loop); } loop(); })() Simple little setup with a function that will loop. In the first few lines we assign: our canvas' context to a $ variable window.innerWidth and innerHeight to our canvas' c.width and c.height and then to our little single-symbol variables w and h. opts as an object that will store some values that you can tweak to your preference later. arr is undefined. Yet. What is arr? It will be the array that will store our particles, that we can loop through, update, and draw each particle. Let's define it. We will use the same strategy as I used in two previous tutorials: initialising the array and defining it's contents dynamically with .map() at the same time. let arr = new Array(opts.amount /* 20 */ ).fill().map((el,ind)=>{ return { a: Math.PI*2/opts.amount * ind, //angle x: (opts.radius*2 /* 10*2 */ + opts.distance /* 10 */)*ind, //horizontal position c: "hsl(th, 75%, 55%)" //color } }) There is kind of a lot of stuff going on here, so let's get through it step by step. Sidenote. As you see the opts object references in the code, please go to the opts object and put in the value that you want/see here. Coming back and going over each value that we mention defined here is pointless. Array processing We create an array. The array is empty (!) even though it has the length of opts.amount. The map() function maps through each object in the array and returns a new one if return is specified. We can't run the function map() yet because, as I mentioned, the arr is empty, hence there is nothing to map through. We fill() the array with undefined elements. Even though each element in the array is still undefined, it is there and the array is not empty anymore. We map() through each undefined object in the array and return a new object that we are going to discuss right now. Particle values Angle is a value between 0 and Math.PI*2, with a step multiplied by the ind (id) of the particle, according to the arr. Position will be a value of distance and radius*2 of particle Color just an hsl color value that I liked. We will later replace the th (theta), hue angle, with the angle of the particle, to make the hue rotate (a bit of a spoiler) Let's update and render It is going to bit all fit into one forEach function to update and render our particles. The background rendering have been defined in the initial setup, so we will just get to the particles arr.forEach(el=>{ //step #1 el.a+= Math.PI/180*4; //step #2 $.beginPath(); $.arc(el.x, Math.sin(el.a)*opts.height, opts.radius, 0, Math.PI*2); $.closePath(); //step #3 $.fillStyle=el.c.replace("th", el.a*20); $.fill(); }); I have defined some steps in the code comments so you know which line to look at. Step #1 el.a += Math.PI/180*4;. Looks a bit confusing if you haven't done that yet. We are taking an angle of the element and incrementing it by 4 degrees. To get degrees here, we convert radians into one degree and then multiply by 4. You can tweak the division part, but visually, it is easier for me to understand degrees over radians. Step #2 This one is not complicated either. As I explained previously, we are using Math.sin as a function that will return a Y coordinate. The reason why we are multiplying that coordinate by opts.height, is because Math.sin returns a value between -1 and 1. If we multiply it by the height it will go height px up and height px below the middle line. So, when you define opts.height consider the fact that the actual animation will be twice as tall. Step #3 This step is used for filling our shape with the dynamic color. The color is defined by the hue angle, which is our element's angle. But because our angle is in Radians, the hue will transition too slowly to notice the "hue wave". To fix that we multiply the angle by a certain number. The bigger the number - the faster the hue rotation. I picked 20 as a multiplier. But wait, I just saved my file and I don't see my particles in the center. Yes, particles are located on top left part of the screen. They aren't rendered as showed on the example. And the reason is because we haven't centered them yet. Doing that will be easy. The center of the screen is usually X: width/2, Y: height/2 coordinate. Our window's Height and Width values are stored in w and h variables. So to render our animation in the middle we will add the center values to our X and Y of the particle in the rendering step like this: $.arc( /* X: */ el.x + w/2, /* Y: */ Math.sin(el.a)*opts.height + h/2, opts.radius, 0, Math.PI*2); It is still not in the center tho... It is shifted to the right of the screen, because the width of our animation incremenets with the amount of particles, but the incremention starts from the middle of the screen and goes far and beyond (depending on the amount of particles you have). To fix that we have to get the width of the whole block of our particles. To do that we can just add the width+distance of each article together by multiplying the radius, distance and amount of them together. let width = opts.amount*( opts.distance + opts.radius*2 ); now to make it work we just have to divide it by 2 and subtract that amount from the center point: $.arc( el.x + w/2 - width/2, /* the rest of the code */ ) And at this moment we should be done :) This is our result: 收起
显示全部文字 查看全文
作者/Godje
时间/2018-01-16 20:41:50

What Every Developer Should Know About Cryptocurrency

We cover the basic cryptocurrency terminology, take a look at the most popular coins, and share some useful libraries and tools.
查看全文
作者/Georgi Georgiev
时间/2018-01-16 19:15:10

Creating Pure CSS Images

I completed Codevember a while ago and created some CSS images during the month of November. Since then, I wanted to share my process on how I create art with CSS. I was not familiar with Codevember until I saw what people were creating on CodePen. I was instantly inspired and wanted to join! Though creating something each day seemed like a challenge, I decided to go for it and ended up having fun. Centering the image First, I use the code below when starting my Codevember projects. html, body { min-height: 100vh; display: grid; } body { display: flex; flex: 1; align-items: center; justify-content: center; } However, I actually do not have a definitive template as there are many methods to centering things. This pen by themarkappleby shows many ways of centering with CSS. .container { margin: auto; width: 20rem; height: 20rem; } Next, I set the width and height of the container. Think of it as a box and fit each shape within the dimensions of the container. I recommend setting both properties to a maximum of 20rem (or 320px) if needed. I find it a good idea to be sure that the CSS image can be viewed on most devices, including mobile. The smallest mobile device width is 320px and I find that using 20rem or below for the width and height has the image fit inside the container without clipping. Working with shapes When it comes to actually creating the CSS image, the biggest tip I can give is to think building and putting the image together with shapes. I usually doodle the image in a sketch book to get an idea of what kinds of shapes I am going to code. Outlined in red are the shapes. Essentially, this CSS image was made with some <div> tags of shapes with different properties such as width, height, border-radius, transform, etc. Just add style to your CSS art with what you want and see what you can come up with! There are different ways of making shapes in CSS. It does not have to be complicated. I try to work as simple as I can. With some trial and error, I get the shapes down to how I like and finally I add colors to them. Sometimes I add gradients and animations to my CSS images too. Then there are some complex shapes like the one. There are curves to the sides of the sword. I tend to choose a flat color for my background (in this case would be #1c2a4a) to create dividers with that same color to make the curved shape. .shape.left::after { top: -1rem; left: -1.5rem; width: 2rem; height: 9.75rem; background: #1c2a4a; border-radius: 100%; } .shape.right::after { top: -1rem; left: 2.5rem; width: 2rem; height: 9.75rem; background: #1c2a4a; border-radius: 100%; } Conclusion Overall I found it all to be a great learning experience. Having daily coding challenges like Codevember has caused me not to spend too much time on each image and to just have fun with creative coding. Below are some great resources to learn more about CSS images! How I started drawing CSS Images by Sasha Tran My journey with pure CSS images by Eleftheria Batsou Learning CSS through Creating Art by Ali Spittel Please feel free to share this post. I hope I was able to inspire someone out there to have fun and code. You can view more what I did for Codevember here. You can reach me at my website, Twitter, Github, Dribbble, and of course CodePen!收起
显示全部文字 查看全文
作者/Katherine Kato
时间/2018-01-12 19:24:16

Nerv - A Fast React 16-Compatible React Alternative

This week's JavaScript news — Read this e-mail on the Web JavaScript Weekly Issue 368 — January 12, 2018 TC39 to Recommend 'Consistently Explicit Semicolon Use'? ..rather than relying on automatic semicolon insertion, as future language developments may affect the situations where ASI works. Brendan Eich signalled his dissent, causing some debate - with many thinking TC39 could recommend the use of a linter instead. Ecma TC39 The Brutal Lifecycle of JavaScript Frameworks Every now and then, a new framework pops up claiming it will revolutionize development. Until the next one. Stack Overflow looks at such lifecycles based on questions asked on its service. Ian Allen Nerv: A Fast React 16-Compatible React Alternative Nerv bills itself as a tinier, faster React alternative and has browser compatibility as a particular focus, supporting right back to IE8. Li Weitao See Why Facebook, Spotify, & Fastlane Trust CircleCI with Their CI/CD Automate the software development process using continuous integration and continuous delivery so you can focus on what matters: building great things, not waiting for great things to build. CircleCI   Sponsor Functional-Light JavaScript: A Balanced Book on FP in JS Kyle Simpson’s written an interesting book that takes a pragmatic look at functional programming concepts in JavaScript. And, yes, you can read it all on GitHub. Kyle Simpson React, Redux and JavaScript Architecture A gentle, but thorough, walkthrough of writing good React and Redux code and, crucially, the why behind each step. James Sinclair Workerize: Run A Module in a Web Worker Moves a module into a Web Worker, automatically reflecting exported functions as asynchronous proxies. There’s workerize-loader for Webpack users, too. Jason Miller TOAST UI Editor: A Markdown WYSIWYG Editor for the Web Works with GitHub Flavored Markdown (GFM) but can be extended with your own extensions. Supports all major browsers (IE10+). GitHub repo. NHN Entertainment Jobs Fullstack Software Engineer (Chicago — Relocation Available)Join a team that cares about people & craft. We invest in you and together we'll solve some of the most interesting problems you've seen. Fraight AI Visual Analytics Researchers and Software Developers - Vienna, AustriaJoin our team and develop novel Web intelligence solutions for EU and Google Digital News Initiative projects (JavaScript, Java). webLyzard technology Looking for a Job at a Company That Prioritizes JavaScript?Try Vettery and we’ll connect you directly with thousands of companies looking for talented front-end devs. Vettery Can't find the right job? Want companies to apply to you? Try Hired.com.-->In Brief Webpack 4 to Work 'Configless' by Default news Inspired by Parcel’s approach.John-David Dalton on Twitter JSON Tree Shaking Landing in Webpack 4.0 news It’s shaping up to be an interesting release. 6 Tiny But Awesome ES7 + ES8 Features tutorialDavid Walsh Building a Real Time Chat App From Scratch using TypeScript tutorialLuis Aviles Build Your First Vue.js Component tutorialSarah Dayan An Introduction to Algebraic Data Types and Structural Pattern Matching in TypeScript tutorialErin Swenson-Healey Learn How to Visualize Your Time Series Data With InfluxDB & Rickshaw tutorial Visualize your time series data from the fastest growing open source TSDB.InfluxData  Sponsor 5 Traps to Avoid While Unit Testing Vue.js tutorialAurélien Bottazini Googlebot's JavaScript random() Function is Deterministic story Probably not useful, but an interesting quirk.Tom Anthony Things to Consider When Choosing a Database for Your JavaScript App Not all JSON support is created equal.mongodb  Sponsor ngrev: Tool for Reverse Engineering/Navigating Angular Projects toolsMinko Gechev InfiniteGrid: Arrange Card Elements Infinitely on a Grid Layout code GitHub repo.NAVER Polythene: A Material Design Component Library for Mithril and React codeArthur Clemens match-sorter: Simple, Expected, & Deterministic Best-Match Array Sorting codeKent C. Dodds SweetAlert: Attractive Modal Popup Alerts/Messages code KaTeX: Fast Math Typesetting for the Web code Easy-to-use library for TeX math rendering on the web.Khan Academy JavaScript Test Results Displayed Inline in Your Editor as You Type  Wallaby.js  Sponsor P.S. Wondering where all the React items are? They're in our React newsletter! Check out the latest issue here. Curated by Peter Cooper and published by Cooperpress. Like this? You may also enjoy: FrontEnd Focus : Node Weekly : React Status Stop getting JavaScript Weekly : Change email address : Read this issue on the Web © Cooperpress Ltd. Fairfield Enterprise Centre, Lincoln Way, Louth, LN11 0LS, UK 收起
显示全部文字 查看全文
作者/
时间/2018-01-12 00:00:00

15 Interesting JavaScript and CSS Libraries for January 2018

A collection of some of the most interesting libraries for January.
查看全文
作者/Georgi Georgiev
时间/2018-01-09 17:26:10

Further protecting users from deceptive or confusing inline installation

Since 2012, Chrome has enabled extension developers to provide a smooth installation experience on their own pages using inline installation. We have also worked hard to prevent abuse of this feature by disabling inline installation in cases where we detect misleading or deceptive installation flows. User complaints have been reduced by 65% since the start of this disabling initiative. Fewer than 3% of extensions still engage in these deceptive or confusing install flows, but this subset of extensions generates 90% more user complaints on average than the rest of the extensions in the Chrome Web Store.As part of our ongoing efforts to protect users, we are expanding our abuse protections to further reduce user harm. Starting in a few weeks, we will upgrade our automated inline installation abuse detection to improve our detection speed and better detect extensions using deceptive or confusing installation flows.In addition to the existing extension-level protection, our expanded enforcement will also use machine learning to evaluate each inline installation request for signals of deceptive, confusing, or malicious ads or webpages. When we find those signals, we’ll selectively disable that one inline installation request and redirect the user to the extension’s page on the Chrome Web Store. This selective enforcement will not impact inline installation of that extension from other, non-deceptive sources.We’ve taken these measures to preserve a good experience for Chrome users and developers in the Chrome Web Store. More information is available in the Inline Installation Enforcement FAQ.Posted by Nav Jagpal and Benjamin Ackerman, Safe Browsing Team收起
显示全部文字 查看全文
作者/Chrome Blog
时间/2018-01-05 06:07:45