Convert Figma logo to code with AI

strawdynamics logodrift

Easily add "zoom on hover" functionality to your site's images. Lightweight, no-dependency JavaScript.

1,536
123
1,536
16

Top Related Projects

3,844

A fast library for AutoML and tuning. Join our Discord: https://discord.gg/Cppx2vSPVP.

10,484

A hyperparameter optimization framework

2,340

Adaptive Experimentation Platform

An open source python library for automated feature engineering

Python package for AutoML on Tabular Data with Feature Engineering, Hyper-Parameters Tuning, Explanations and Automatic Documentation

9,653

A Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.

Quick Overview

Drift is a lightweight, high-performance game engine written in Rust. It focuses on providing a simple and efficient framework for game development, leveraging Rust's safety features and performance capabilities.

Pros

  • Fast and efficient due to Rust's performance characteristics
  • Memory-safe and thread-safe, reducing common game development bugs
  • Modular design allows for easy extension and customization
  • Cross-platform support for desktop and web targets

Cons

  • Limited documentation and examples compared to more established game engines
  • Smaller community and ecosystem compared to popular alternatives
  • Steeper learning curve for developers not familiar with Rust
  • Still in early development stages, potentially lacking some advanced features

Code Examples

  1. Creating a basic window:
use drift::prelude::*;

fn main() {
    let mut app = App::new();
    app.add_plugin(WindowPlugin::default());
    app.run();
}
  1. Adding a simple 2D sprite:
use drift::prelude::*;

fn main() {
    let mut app = App::new();
    app.add_plugin(WindowPlugin::default());
    app.add_plugin(SpritePlugin::default());
    
    app.add_startup_system(setup);
    app.run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(SpriteBundle {
        texture: asset_server.load("sprite.png"),
        ..default()
    });
}
  1. Implementing basic movement:
use drift::prelude::*;

fn main() {
    let mut app = App::new();
    app.add_plugin(WindowPlugin::default());
    app.add_plugin(SpritePlugin::default());
    
    app.add_startup_system(setup);
    app.add_system(move_sprite);
    app.run();
}

fn setup(mut commands: Commands) {
    commands.spawn((
        SpriteBundle::default(),
        Velocity { x: 1.0, y: 1.0 },
    ));
}

fn move_sprite(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
    for (mut transform, velocity) in query.iter_mut() {
        transform.translation.x += velocity.x * time.delta_seconds();
        transform.translation.y += velocity.y * time.delta_seconds();
    }
}

struct Velocity {
    x: f32,
    y: f32,
}

Getting Started

To get started with Drift, follow these steps:

  1. Install Rust and Cargo (Rust's package manager)
  2. Create a new Rust project: cargo new my_game
  3. Add Drift as a dependency in your Cargo.toml:
    [dependencies]
    drift = "0.1"
    
  4. Use the code examples above as a starting point for your game
  5. Run your game with cargo run

For more detailed information and advanced usage, refer to the Drift documentation and examples in the GitHub repository.

Competitor Comparisons

3,844

A fast library for AutoML and tuning. Join our Discord: https://discord.gg/Cppx2vSPVP.

Pros of FLAML

  • More comprehensive AutoML toolkit with support for various tasks (classification, regression, forecasting, etc.)
  • Active development and maintenance by Microsoft, with frequent updates and improvements
  • Extensive documentation and examples available

Cons of FLAML

  • Steeper learning curve due to more complex API and features
  • Potentially higher computational requirements for large-scale tasks
  • May be overkill for simpler machine learning projects

Code Comparison

FLAML example:

from flaml import AutoML
automl = AutoML()
automl.fit(X_train, y_train, task="classification")
predictions = automl.predict(X_test)

Drift example:

from drift import DriftModel
model = DriftModel()
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Summary

FLAML offers a more comprehensive AutoML solution with support for various tasks and active development by Microsoft. However, it may have a steeper learning curve and higher computational requirements. Drift, on the other hand, appears to be a simpler, more focused library for specific machine learning tasks. The choice between the two depends on the project's complexity and requirements.

10,484

A hyperparameter optimization framework

Pros of Optuna

  • More mature and widely adopted project with extensive documentation
  • Supports a broader range of optimization algorithms and techniques
  • Offers built-in visualization tools for analyzing optimization results

Cons of Optuna

  • Steeper learning curve due to more complex API and features
  • Potentially slower for simple optimization tasks due to additional overhead

Code Comparison

Optuna example:

import optuna

def objective(trial):
    x = trial.suggest_float('x', -10, 10)
    return (x - 2) ** 2

study = optuna.create_study()
study.optimize(objective, n_trials=100)

Drift example:

from drift import Drift

def objective(x):
    return (x - 2) ** 2

drift = Drift(objective)
result = drift.minimize(bounds=[(-10, 10)])

Both libraries aim to simplify hyperparameter optimization, but Optuna offers more advanced features and flexibility, while Drift focuses on simplicity and ease of use for basic optimization tasks. Optuna is better suited for complex projects requiring advanced optimization techniques, whereas Drift may be preferable for simpler use cases or when getting started with hyperparameter tuning.

2,340

Adaptive Experimentation Platform

Pros of Ax

  • More comprehensive and feature-rich platform for adaptive experimentation
  • Backed by Facebook, with extensive documentation and community support
  • Integrates well with other machine learning libraries like PyTorch

Cons of Ax

  • Steeper learning curve due to its complexity
  • Heavier resource requirements for installation and usage
  • May be overkill for simpler optimization tasks

Code Comparison

Ax example:

from ax import optimize

def evaluation_function(parameterization):
    x = parameterization["x"]
    return {"objective": (x - 2) ** 2}

best_parameters, values, experiment, model = optimize(
    parameters=[{"name": "x", "type": "range", "bounds": [-10, 10]}],
    evaluation_function=evaluation_function,
    objective_name="objective",
)

Drift example:

from drift import Drift

def objective(x):
    return (x - 2) ** 2

drift = Drift(objective)
result = drift.minimize(bounds=[(-10, 10)])

Summary

Ax offers a more comprehensive platform for advanced experimentation, while Drift provides a simpler, more lightweight approach to optimization. Ax is better suited for complex, large-scale projects, whereas Drift may be preferable for quick, straightforward optimization tasks. The choice between the two depends on the specific requirements and complexity of the project at hand.

An open source python library for automated feature engineering

Pros of Featuretools

  • More comprehensive feature engineering capabilities, including automated feature generation
  • Larger community and more active development, with frequent updates and improvements
  • Extensive documentation and examples for various use cases

Cons of Featuretools

  • Steeper learning curve due to more complex API and concepts
  • Higher computational resources required for large datasets
  • Less focus on drift detection and monitoring compared to Drift

Code Comparison

Featuretools:

import featuretools as ft
es = ft.EntitySet(id="example")
es = es.add_dataframe(dataframe=df, dataframe_name="data")
feature_matrix, feature_defs = ft.dfs(entityset=es, target_entity="data")

Drift:

from drift import DriftDetector
detector = DriftDetector()
detector.fit(reference_data)
drift_score = detector.score(new_data)

Summary

Featuretools excels in automated feature engineering and has a larger ecosystem, while Drift focuses on drift detection and monitoring. Featuretools offers more comprehensive capabilities but may require more resources and learning time. Drift provides a simpler API for specific drift-related tasks. The choice between them depends on the primary use case and available resources.

Python package for AutoML on Tabular Data with Feature Engineering, Hyper-Parameters Tuning, Explanations and Automatic Documentation

Pros of mljar-supervised

  • More comprehensive AutoML solution with support for various ML tasks
  • Extensive documentation and examples for easier adoption
  • Active development and community support

Cons of mljar-supervised

  • Larger codebase and dependencies, potentially more complex to integrate
  • May have higher computational requirements for full AutoML pipeline

Code Comparison

mljar-supervised:

from supervised import AutoML

automl = AutoML(results_path="automl_results")
automl.fit(X, y)
predictions = automl.predict(X_test)

drift:

from drift import DriftDetector

detector = DriftDetector()
detector.fit(X_train)
drift_score = detector.score(X_test)

Key Differences

  • mljar-supervised focuses on end-to-end AutoML, while drift specializes in drift detection
  • drift has a simpler API and is more lightweight, suitable for specific drift detection tasks
  • mljar-supervised offers more features and flexibility for general machine learning workflows

Use Cases

  • Choose mljar-supervised for comprehensive AutoML solutions and diverse ML tasks
  • Opt for drift when specifically dealing with data drift detection in production environments
9,653

A Python Automated Machine Learning tool that optimizes machine learning pipelines using genetic programming.

Pros of TPOT

  • More mature and widely adopted project with a larger community
  • Supports a broader range of machine learning algorithms and preprocessing methods
  • Offers built-in cross-validation and feature selection capabilities

Cons of TPOT

  • Can be slower and more computationally intensive, especially for large datasets
  • Less flexible for custom pipeline components and optimization strategies
  • Steeper learning curve for users new to automated machine learning

Code Comparison

TPOT example:

from tpot import TPOTClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

tpot = TPOTClassifier(generations=5, population_size=20, verbosity=2)
tpot.fit(X_train, y_train)
print(tpot.score(X_test, y_test))

Drift example:

from drift import DriftClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

drift = DriftClassifier()
drift.fit(X_train, y_train)
print(drift.score(X_test, y_test))

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Drift

Drift adds easy "zoom on hover" functionality to your site's images, all with lightweight, no-dependency JavaScript.

npm version Build Status npm License styled with prettier All Contributors FOSSA Status


Installation

  • NPM: npm install drift-zoom
  • Bower: bower install drift
  • Manual: Download and use dist/Drift.min.js or dist/Drift.js

If you're using the pre-built version of Drift, it will automatically make window.Drift available for your use when included on your page.

If you prefer to use require statements and a build tool like Browserify, here are a couple examples to help:

var Drift = require('drift-zoom');

new Drift(…);

If your project uses ES6, you can do the following instead:

import Drift from 'drift-zoom';

new Drift(…);

Basic Usage

Once you've installed Drift via one of the above methods, you're ready to get started. There are no dependencies, so you can just start making cool stuff. Check out the announcement blog post. Here's an example of a basic implementation:

<img src="https://assets.imgix.net/dog.png?w=400" data-zoom="https://assets.imgix.net/dog.png?w=1200">

<p>This is a simple description of the dog picture.</p>
new Drift(document.querySelector("img"), {
  paneContainer: document.querySelector("p")
});

Demo 💻💻💻

Take a peek at our Demo Site.

Options / Defaults

Here's an example of using Drift with a custom configuration. All of the listed options are displayed with their default value.

var options = {
	// Prefix for generated element class names (e.g. `my-ns` will
	// result in classes such as `my-ns-pane`. Default `drift-`
	// prefixed classes will always be added as well.
	namespace: null,
	// Whether the ZoomPane should show whitespace when near the edges.
	showWhitespaceAtEdges: false,
	// Whether the inline ZoomPane should stay inside
	// the bounds of its image.
	containInline: false,
	// How much to offset the ZoomPane from the
	// interaction point when inline.
	inlineOffsetX: 0,
	inlineOffsetY: 0,
	// A DOM element to append the inline ZoomPane to.
	inlineContainer: document.body,
	// Which trigger attribute to pull the ZoomPane image source from.
	sourceAttribute: 'data-zoom',
	// How much to magnify the trigger by in the ZoomPane.
	// (e.g., `zoomFactor: 3` will result in a 900 px wide ZoomPane image
	// if the trigger is displayed at 300 px wide)
	zoomFactor: 3,
	// A DOM element to append the non-inline ZoomPane to.
	// Required if `inlinePane !== true`.
	paneContainer: document.body,
	// When to switch to an inline ZoomPane. This can be a boolean or
	// an integer. If `true`, the ZoomPane will always be inline,
	// if `false`, it will switch to inline when `windowWidth <= inlinePane`
	inlinePane: 375,
	// If `true`, touch events will trigger the zoom, like mouse events.
	handleTouch: true,
	// If present (and a function), this will be called
	// whenever the ZoomPane is shown.
	onShow: null,
	// If present (and a function), this will be called
	// whenever the ZoomPane is hidden.
	onHide: null,
	// Add base styles to the page. See the "Theming"
	// section of README.md for more information.
	injectBaseStyles: true,
	// An optional number that determines how long to wait before
	// showing the ZoomPane because of a `mouseenter` event.
	hoverDelay: 0,
	// An optional number that determines how long to wait before
	// showing the ZoomPane because of a `touchstart` event.
	// Setting this to a reasonable amount will allow users to execute
	// scroll-gestures events on touch-enabled devices with the image as
	// a starting point
	touchDelay: 0,
	// If true, a bounding box will show the area currently being previewed
	// during mouse hover
	hoverBoundingBox: false,
	// If true, a bounding box will show the area currently being previewed
	// during touch events
	touchBoundingBox: false,
	// A DOM element to append the bounding box to.
	boundingBoxContainer: document.body,
	// If true, the events related to handleTouch use passive listeners in
	// order to improve performance for touch devices.
	passive: false,
};

new Drift(document.querySelector('img'), options);

API

Drift#disable

Disable your Drift instance. This will prevent your Drift instance from showing, but will not hide it if it's currently visible.

var drift = new Drift(document.querySelector("img"), {
  paneContainer: document.querySelector("p")
});

document.querySelector(".disable-button").addEventListener("click", function() {
  drift.disable();
});

Drift#enable

Enable your Drift instance.

var drift = new Drift(document.querySelector("img"), {
  paneContainer: document.querySelector("p")
});

document.querySelector(".enable-button").addEventListener("click", function() {
  drift.enable();
});

Drift#setZoomImageURL(imageURL)

Change the URL of the zoom image to the passed string. This only has a visible effect while your Drift is currently open. When opening, Drift always pulls the zoom image URL from the specified sourceAttribute. If you want to make a "permanent" change that will persist after the user leaves and re-enters your Drift trigger, you update its sourceAttribute as well (default data-zoom). For more information about this method, please see issue #42.

var triggerEl = document.querySelector("img");
var drift = new Drift(triggerEl, {
  paneContainer: document.querySelector("p")
});

var frames = ["https://mysite.com/frame1.jpg", "https://mysite.com/frame2.jpg", "https://mysite.com/frame3.jpg"];

var currentFrame = 0;

setInterval(function() {
  currentFrame++;

  if (currentFrame > frames.length - 1) {
    currentFrame = 0;
  }

  drift.setZoomImageURL(frames[currentFrame]);
  triggerEl.setAttribute("data-zoom", frames[currentFrame]);
}, 1200);

Theming

By default, Drift injects an extremely basic set of styles into the page. You will almost certainly want to extend these basic styles for a prettier, more usable experience that matches your site. There is an included basic theme that may meet your needs, or at least give a good example of how to build out your own custom styles. The namespace option can be used as a way to easily apply different themes to specific instances of Drift.

If you need to do something very out of the ordinary, or just prefer to include the default styles in CSS yourself, you can pass injectBaseStyles: false when instantiating a new instance of Drift. Please note that if you disable the included base styles, you will still need to provide an animation for .drift-window.drift-opening and .drift-window.drift-closing (this can be a "noop" style animation, as seen in the base styles source).

FAQs/Examples

In this section we answer common questions about Drift.

Disabling on Mobile

If you would like the touch events not to fire on mobile for one reason or another, these two solutions should work for you.

CSS Solution (Recommended)

This solution places a transparent element over the image on mobiles to block touch events. Replace 1024px in the media query with your mobile breakpoint.

.zoom-image {
	position: relative;
}

.zoom-image::before {
	content: "";
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: transparent;
}

@media only screen and (min-width: 1024px) {
	.zoom-image::before {
		display: none;
	}
}

JS Solution

This solution creates and destroys the Drift instance when the browser size changes. It depends on the library responsive.js but can easily be altered to use vanilla JS.

const driftOptions = {
	paneContainer: paneContainer,
	inlinePane: false,
	handleTouch: false
};

const handleChange = () => {
	requestAnimationFrame(() => {
		if (Responsive.is('mobile') && !!window.productZoom) {
			window.productZoom.destroy();
		} else {
			window.productZoom = new Drift(img, driftOptions);
		}
	})
}

window.addEventListener('resize', handleChange);
window.addEventListener('load', handleChange);

Use Drift with Multiple Images on the Same Page

This code will iterate over all elements on your page with the class drift-img, and will instantiate Drift for each element. You can update the query selector and pane as you see fit.

const driftImgs = document.querySelectorAll('.drift-img');
const pane = document.querySelector('.drift-pane');
driftImgs.map(img => {
	new Drift(img, {
		paneContainer: pane,
		inlinePane: false
	});
});

Browser Support

We support the latest version of Google Chrome (which automatically updates whenever it detects that a new version of the browser is available). We also support the current and previous major releases of desktop Firefox, Internet Explorer, and Safari on a rolling basis. Mobile support is tested on the most recent minor version of the current and previous major release for the default browser on iOS and Android (e.g., iOS 9.2 and 8.4). Each time a new version is released, we begin supporting that version and stop supporting the third most recent version.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Paul Straw

📖 💻 🚧

sherwinski

💻 📖 🚧

Frederick Fogerty

💻 📖 🚧

Jason Eberle

💻 📖 🚧

Luis H. Ball Jr.

🚧

This project follows the all-contributors specification. Contributions of any kind welcome!

Meta

Drift was made by imgix. It's licensed under the BSD 2-Clause license (see the license file for more info). Any contribution is absolutely welcome, but please review the contribution guidelines before getting started.

License

FOSSA Status