npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

use-capture-element

v1.0.7

Published

Hook de React y Next.js para capturar elementos HTML como imagen utilizando html2canvas.

Downloads

22

Readme

useCaptureElement

Un hook personalizado para React y Next.js que facilita la captura de imágenes de elementos HTML utilizando html2canvas. Ideal para generar capturas de pantalla de componentes o secciones específicas de tu aplicación.

🚀 Instalación

Para instalar el paquete en tu proyecto, ejecuta:

npm install use-capture-element

📌 Uso Básico

Importa el hook useCaptureElement en tu componente y úsalo para capturar cualquier elemento HTML.

📝 Ejemplo: Capturar un elemento HTML

import { useRef } from "react";
import { useCaptureElement } from "use-capture-element";

export default function Example() {
  const ref = useRef<HTMLDivElement>(null);
  const { generateImage } = useCaptureElement();

  return (
    <div className="flex flex-col items-center gap-4">
      <div
        ref={ref}
        className="p-4 border rounded-lg shadow-md bg-gray-100 text-center"
      >
        Este elemento será capturado como una imagen.
      </div>
      <button
        onClick={() => generateImage(ref, "captura.png")}
        className="px-4 py-2 bg-blue-500 text-white rounded-md"
      >
        Capturar Elemento
      </button>
    </div>
  );
}

⚙️ API del Hook

El hook useCaptureElement expone la siguiente función:

📌 generateImage(ref, fileName, excludeSelector?)

| Parámetro | Tipo | Descripción | |------------------|----------------------------|-------------| | ref | RefObject<HTMLElement> | Referencia al elemento HTML que se va a capturar. | | fileName | string (opcional) | Nombre del archivo de la imagen generada. (Por defecto: "image.png") | | excludeSelector | string (opcional) | Selector CSS para excluir elementos específicos de la captura. |

📌 Nota: Si excludeSelector se proporciona, todos los elementos que coincidan con el selector serán excluidos de la captura.

🛠 Ejemplo Avanzado: Excluir elementos específicos

Si deseas excluir ciertos elementos de la captura, puedes usar excludeSelector:

import { useRef } from "react";
import { useCaptureElement } from "use-capture-element";

export default function AdvancedExample() {
  const ref = useRef<HTMLDivElement>(null);
  const { generateImage } = useCaptureElement();

  return (
    <div className="flex flex-col items-center gap-4">
      <div
        ref={ref}
        className="p-4 border rounded-lg shadow-md bg-gray-100 text-center"
      >
        <p>Este elemento será capturado con alta calidad.</p>
        <div className="hidden-element text-red-500">Este no aparecerá en la captura.</div>
      </div>
      <button
        onClick={() => generateImage(ref, "high-quality-capture.png", ".hidden-element")}
        className="px-4 py-2 bg-green-500 text-white rounded-md"
      >
        Capturar sin elementos ocultos
      </button>
    </div>
  );
}

📢 Nota: Todos los elementos con la clase .hidden-element serán excluidos de la captura.

🎨 Características

  • 📸 Captura de elementos HTML → Convierte cualquier elemento HTML en una imagen en formato PNG.
  • ✂️ Exclusión de elementos → Permite excluir elementos específicos de la captura mediante un selector CSS.
  • 🖼️ Escalado de calidad → Usa scale: 1.5 por defecto para mejorar la calidad de la imagen.
  • Fácil de usar → Solo necesitas una referencia (ref) y un botón para capturar el contenido.

🤝 Contribuciones

¡Las contribuciones son bienvenidas! 🎉

Si quieres mejorar el hook, sigue estos pasos:

  1. Forkea el repositorio y clónalo en tu máquina local.
  2. Crea una nueva rama para tu cambio:
git checkout -b feature/nueva-funcionalidad
  1. Realiza cambios y haz un commit descriptivo:
git commit -m "Agregada nueva funcionalidad X"
  1. Sube tu rama y abre un Pull Request (PR) hacia main.
    📌 Para más detalles, consulta la guía de contribución:
    🔗 CONTRIBUTING.md

Si encuentras un error, repórtalo en los Issues:
🔗 Abrir un nuevo Issue

📜 Licencia

Este proyecto está bajo la licencia MIT. Consulta el archivo LICENSE para más detalles.