Compare commits

70 Commits

Author SHA1 Message Date
883c93b7ff [FEAT] Add Kofi btn 2025-12-12 14:57:41 +01:00
b255acce40 [FEAT] Package updates 2025-12-11 21:27:01 +01:00
f52530d058 [FEAT] New Discord 2025-12-01 02:25:53 +01:00
bf95f4fbee UX enhancements 2025-11-26 20:29:30 +01:00
c4a0024ec0 [FEAT] Performance enhancements 2025-11-26 19:53:55 +01:00
8a86ae3e98 [FEAT] Fix link alignment 2025-11-26 19:51:35 +01:00
233aab5350 [FEAT] SEO fix 2025-11-26 19:42:20 +01:00
cfef7d30aa [FEAT] Add FAQ to sitemap 2025-11-26 19:38:03 +01:00
04ab97b15c [FEAT] FAQ update 2025-11-26 19:33:50 +01:00
14dbb17ba2 [FEAT] H1 > span 2025-11-26 19:30:26 +01:00
75e24eac42 [FEAT] Add FAQ 2025-11-26 19:27:33 +01:00
0942ce5d51 [FEAT] Typo 2025-11-26 18:01:08 +01:00
fd43c7b515 [FEAT] Update PP 2025-11-26 18:00:16 +01:00
2d4a7e3765 [FEAT] Add ads.txt 2025-11-26 17:41:13 +01:00
84428b3196 [FEAT] Added missing types 2025-11-26 17:29:38 +01:00
c448a4c267 [FEAT] Add gradient 2025-11-26 17:26:42 +01:00
80787719e6 [FEAT] New article 2025-11-26 17:24:32 +01:00
b801cd4c99 [FEAT] SEO best practices 2025-11-26 17:20:09 +01:00
accea99408 [FEAT] Fix vue warn 2025-11-26 17:16:52 +01:00
09c77f5414 BReadcrumbs 2025-11-26 17:13:42 +01:00
d38ba85f4f [FEAT] SEO labels 2025-11-26 17:05:01 +01:00
54ef9121c7 [FEAT] Add blog 2025-11-26 16:41:39 +01:00
7152482687 [FEAT] Added vue router and pages 2025-11-26 15:59:34 +01:00
107caef54d [FEAT] DA 2025-11-26 15:36:11 +01:00
5ca0a0ea78 [FEAT] Btn size fix 2025-11-26 14:09:24 +01:00
f9986b319d [FEAT] More UI enhancements 2025-11-26 14:04:21 +01:00
df6758d112 [FEAT] Add robots.txt and sitemap 2025-11-25 20:37:19 +01:00
00cee9e593 [FEAT] Add license file 2025-11-25 19:12:31 +01:00
70090f3a6c [FEAT] New vid. 2025-11-25 18:51:15 +01:00
4bbe797d9b [FEAT] Enhance UI 2025-11-25 18:42:32 +01:00
9717ab9575 [FEAT] Moved buttons for more space 2025-11-25 17:59:09 +01:00
386393e507 [FEAT] Layer bugfix and new demo video 2025-11-25 17:52:49 +01:00
b2f9e7d5b9 [FEAT] Compare sprite bug fix 2025-11-25 17:16:42 +01:00
044c819a09 [FEAT] Add bullet styling to ul 2025-11-25 17:02:03 +01:00
8505e98947 [FEAT] Enhance UI 2025-11-25 16:39:49 +01:00
19d0f3584c [FEAT] Add ad banner 2025-11-25 02:06:13 +01:00
452711a6f9 [FEAT] Bug fix 2025-11-25 01:57:10 +01:00
caef8003fa [FEAT] Bug fix 2025-11-25 01:48:02 +01:00
2586a0a0bc [FEAT] Disable checkerboard bg 2025-11-23 17:32:36 +01:00
a76c0bd04d Fix 2025-11-23 17:26:14 +01:00
551d7a027f [FEAT] Text for SEO 2025-11-23 17:08:20 +01:00
6b0c82a630 [FEAT] Updated colors 2025-11-23 17:03:42 +01:00
a0d2b2994b [FEAT] Allow to toggle checker bg 2025-11-23 15:42:02 +01:00
7f8e26255f [FEAT] Canvas > IMG 2025-11-23 15:40:04 +01:00
4ec82317ea [FEAT] Tab bug fix 2025-11-23 15:11:53 +01:00
fed578441a [FEAT] Fix context menu location 2025-11-23 15:09:28 +01:00
62205ed069 Improved UX 2025-11-23 15:05:03 +01:00
6ae8dd37dc Typos 2025-11-23 14:49:41 +01:00
77a1b22faf Improved min height 2025-11-23 14:40:12 +01:00
8b1ea0f5b4 [FEAT] Preview enhancement 2025-11-23 03:52:57 +01:00
9a2bf6b2db [FEAT] UX enhancements 2025-11-23 03:40:26 +01:00
2c25157621 [FEAT] Remove gradients 2025-11-23 01:57:08 +01:00
9fa2bbd15d [FEAT] Add cursor click 2025-11-23 01:53:16 +01:00
b3f530870e [FEAT] More UI enhancements 2025-11-23 01:48:05 +01:00
56858701ef [FEAT] Enhanced UI 2025-11-23 01:16:58 +01:00
f8b4e98f9c [FEAT] Allow to adjust cell size 2025-11-22 21:33:01 +01:00
69fc4c4a7e [FEAT] BG color enhancements 2025-11-22 18:31:06 +01:00
d35ae69265 [FEAT] Fix incorrect offset val. label placement 2025-11-22 18:09:32 +01:00
aee07f23f2 ## [1.7.0] - 2025-11-22
- Add layer support
- Add background color picker
- Improved UI
2025-11-22 03:19:19 +01:00
474ddd3e27 Perf. fix 2025-11-22 02:58:54 +01:00
097df1f5de POC 2025-11-22 02:52:36 +01:00
5cc4eb8731 [FEAT] negative spacing in JSON export logic, show cell size 2025-11-18 22:18:38 +01:00
57d62db219 Fix for negative spacing 2025-11-18 21:11:26 +01:00
f7a01e6c92 Export negative offset bug fixes 2025-11-18 20:30:59 +01:00
590d76205f Finish clean, add negative spacing toggle 2025-11-18 20:27:06 +01:00
5c33e77595 npm run format 2025-11-18 20:12:32 +01:00
404ca9ce88 Continuation of separting logic into domain specific composables 2025-11-18 20:11:36 +01:00
d571cb51cb Clean 2025-11-18 19:49:25 +01:00
c1620d6bbb Reused logic from earlier made composables 2025-11-18 19:45:53 +01:00
6afbd42794 [FEAT] Began working on cleaning code 2025-11-18 19:40:44 +01:00
50 changed files with 5965 additions and 2216 deletions

View File

@@ -1,16 +1,28 @@
http://spritesheetgenerator.online:1337 { http://spritesheetgenerator.online:1337 {
root * ./dist root * ./dist
encode gzip encode zstd gzip
# Aggressive caching for static assets
@static path *.js *.css *.png *.jpg *.jpeg *.gif *.webp *.svg *.woff *.woff2 *.ico
header @static Cache-Control "public, max-age=31536000, immutable"
# Short cache for HTML (for SPA updates)
@html path *.html /
header @html Cache-Control "no-cache, must-revalidate"
# Default cache for everything else
header ?Cache-Control "max-age=1800"
try_files {path} /index.html try_files {path} /index.html
file_server {
file_server precompressed zstd gzip
}
log { log {
output file /var/log/caddy/spritesheetgenerator.online.log output file /var/log/caddy/spritesheetgenerator.online.log
} }
}
header {
?Cache-Control "max-age=1800" :1338 {
} redir https://spritesheetgenerator.online{uri} permanent
} }

636
LICENSE.md Normal file
View File

@@ -0,0 +1,636 @@
# GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/)
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and
other kinds of works.
The licenses for most software and other practical works are designed to take
away your freedom to share and change the works. By contrast, the GNU General
Public License is intended to guarantee your freedom to share and change all
versions of a program--to make sure it remains free software for all its users.
We, the Free Software Foundation, use the GNU General Public License for most
of our software; it applies also to any other work released this way by its
authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the freedom to
distribute copies of free software (and charge for them if you wish), that you
receive source code or can get it if you want it, that you can change the
software or use pieces of it in new free programs, and that you know you can do
these things.
To protect your rights, we need to prevent others from denying you these rights
or asking you to surrender the rights. Therefore, you have certain
responsibilities if you distribute copies of the software, or if you modify it:
responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for
a fee, you must pass on to the recipients the same freedoms that you received.
You must make sure that they, too, receive or can get the source code. And you
must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps:
1. assert copyright on the software, and
2. offer you this License giving you legal permission to copy, distribute
and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that
there is no warranty for this free software. For both users' and authors' sake,
the GPL requires that modified versions be marked as changed, so that their
problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified
versions of the software inside them, although the manufacturer can do so. This
is fundamentally incompatible with the aim of protecting users' freedom to
change the software. The systematic pattern of such abuse occurs in the area of
products for individuals to use, which is precisely where it is most
unacceptable. Therefore, we have designed this version of the GPL to prohibit
the practice for those products. If such problems arise substantially in other
domains, we stand ready to extend this provision to those domains in future
versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States
should not allow patents to restrict development and use of software on
general-purpose computers, but in those that do, we wish to avoid the special
danger that patents applied to a free program could make it effectively
proprietary. To prevent this, the GPL assures that patents cannot be used to
render the program non-free.
The precise terms and conditions for copying, distribution and modification
follow.
## TERMS AND CONDITIONS
### 0. Definitions.
*This License* refers to version 3 of the GNU General Public License.
*Copyright* also means copyright-like laws that apply to other kinds of works,
such as semiconductor masks.
*The Program* refers to any copyrightable work licensed under this License.
Each licensee is addressed as *you*. *Licensees* and *recipients* may be
individuals or organizations.
To *modify* a work means to copy from or adapt all or part of the work in a
fashion requiring copyright permission, other than the making of an exact copy.
The resulting work is called a *modified version* of the earlier work or a work
*based on* the earlier work.
A *covered work* means either the unmodified Program or a work based on the
Program.
To *propagate* a work means to do anything with it that, without permission,
would make you directly or secondarily liable for infringement under applicable
copyright law, except executing it on a computer or modifying a private copy.
Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To *convey* a work means any kind of propagation that enables other parties to
make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays *Appropriate Legal Notices* to the
extent that it includes a convenient and prominently visible feature that
1. displays an appropriate copyright notice, and
2. tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the work
under this License, and how to view a copy of this License.
If the interface presents a list of user commands or options, such as a menu, a
prominent item in the list meets this criterion.
### 1. Source Code.
The *source code* for a work means the preferred form of the work for making
modifications to it. *Object code* means any non-source form of a work.
A *Standard Interface* means an interface that either is an official standard
defined by a recognized standards body, or, in the case of interfaces specified
for a particular programming language, one that is widely used among developers
working in that language.
The *System Libraries* of an executable work include anything, other than the
work as a whole, that (a) is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and (b) serves only
to enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code
form. A *Major Component*, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on
which the executable work runs, or a compiler used to produce the work, or an
object code interpreter used to run it.
The *Corresponding Source* for a work in object code form means all the source
code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities.
However, it does not include the work's System Libraries, or general-purpose
tools or generally available free programs which are used unmodified in
performing those activities but which are not part of the work. For example,
Corresponding Source includes interface definition files associated with source
files for the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require, such as
by intimate data communication or control flow between those subprograms and
other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on
the Program, and are irrevocable provided the stated conditions are met. This
License explicitly affirms your unlimited permission to run the unmodified
Program. The output from running a covered work is covered by this License only
if the output, given its content, constitutes a covered work. This License
acknowledges your rights of fair use or other equivalent, as provided by
copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey
covered works to others for the sole purpose of having them make modifications
exclusively for you, or provide you with facilities for running those works,
provided that you comply with the terms of this License in conveying all
material for which you do not control copyright. Those thus making or running
the covered works for you must do so exclusively on your behalf, under your
direction and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes it
unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure
under any applicable law fulfilling obligations under article 11 of the WIPO
copyright treaty adopted on 20 December 1996, or similar laws prohibiting or
restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention is
effected by exercising rights under this License with respect to the covered
work, and you disclaim any intention to limit operation or modification of the
work as a means of enforcing, against the work's users, your or third parties'
legal rights to forbid circumvention of technological measures.
### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it,
in any medium, provided that you conspicuously and appropriately publish on
each copy an appropriate copyright notice; keep intact all notices stating that
this License and any non-permissive terms added in accord with section 7 apply
to the code; keep intact all notices of the absence of any warranty; and give
all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may
offer support or warranty protection for a fee.
### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it
from the Program, in the form of source code under the terms of section 4,
provided that you also meet all of these conditions:
- a) The work must carry prominent notices stating that you modified it, and
giving a relevant date.
- b) The work must carry prominent notices stating that it is released under
this License and any conditions added under section 7. This requirement
modifies the requirement in section 4 to *keep intact all notices*.
- c) You must license the entire work, as a whole, under this License to
anyone who comes into possession of a copy. This License will therefore
apply, along with any applicable section 7 additional terms, to the whole
of the work, and all its parts, regardless of how they are packaged. This
License gives no permission to license the work in any other way, but it
does not invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your work need
not make them do so.
A compilation of a covered work with other separate and independent works,
which are not by their nature extensions of the covered work, and which are not
combined with it such as to form a larger program, in or on a volume of a
storage or distribution medium, is called an *aggregate* if the compilation and
its resulting copyright are not used to limit the access or legal rights of the
compilation's users beyond what the individual works permit. Inclusion of a
covered work in an aggregate does not cause this License to apply to the other
parts of the aggregate.
### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4
and 5, provided that you also convey the machine-readable Corresponding Source
under the terms of this License, in one of these ways:
- a) Convey the object code in, or embodied in, a physical product (including
a physical distribution medium), accompanied by the Corresponding Source
fixed on a durable physical medium customarily used for software
interchange.
- b) Convey the object code in, or embodied in, a physical product (including
a physical distribution medium), accompanied by a written offer, valid for
at least three years and valid for as long as you offer spare parts or
customer support for that product model, to give anyone who possesses the
object code either
1. a copy of the Corresponding Source for all the software in the product
that is covered by this License, on a durable physical medium
customarily used for software interchange, for a price no more than your
reasonable cost of physically performing this conveying of source, or
2. access to copy the Corresponding Source from a network server at no
charge.
- c) Convey individual copies of the object code with a copy of the written
offer to provide the Corresponding Source. This alternative is allowed only
occasionally and noncommercially, and only if you received the object code
with such an offer, in accord with subsection 6b.
- d) Convey the object code by offering access from a designated place
(gratis or for a charge), and offer equivalent access to the Corresponding
Source in the same way through the same place at no further charge. You
need not require recipients to copy the Corresponding Source along with the
object code. If the place to copy the object code is a network server, the
Corresponding Source may be on a different server operated by you or a
third party) that supports equivalent copying facilities, provided you
maintain clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the Corresponding
Source, you remain obligated to ensure that it is available for as long as
needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission, provided you
inform other peers where the object code and Corresponding Source of the
work are being offered to the general public at no charge under subsection
6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A *User Product* is either
1. a *consumer product*, which means any tangible personal property which is
normally used for personal, family, or household purposes, or
2. anything designed or sold for incorporation into a dwelling.
In determining whether a product is a consumer product, doubtful cases shall be
resolved in favor of coverage. For a particular product received by a
particular user, *normally used* refers to a typical or common use of that
class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use,
the product. A product is a consumer product regardless of whether the product
has substantial commercial, industrial or non-consumer uses, unless such uses
represent the only significant mode of use of the product.
*Installation Information* for a User Product means any methods, procedures,
authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified
version of its Corresponding Source. The information must suffice to ensure
that the continued functioning of the modified object code is in no case
prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as part of a
transaction in which the right of possession and use of the User Product is
transferred to the recipient in perpetuity or for a fixed term (regardless of
how the transaction is characterized), the Corresponding Source conveyed under
this section must be accompanied by the Installation Information. But this
requirement does not apply if neither you nor any third party retains the
ability to install modified object code on the User Product (for example, the
work has been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates for a
work that has been modified or installed by the recipient, or for the User
Product in which it has been modified or installed. Access to a network may be
denied when the modification itself materially and adversely affects the
operation of the network or violates the rules and protocols for communication
across the network.
Corresponding Source conveyed, and Installation Information provided, in accord
with this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require
no special password or key for unpacking, reading or copying.
### 7. Additional Terms.
*Additional permissions* are terms that supplement the terms of this License by
making exceptions from one or more of its conditions. Additional permissions
that are applicable to the entire Program shall be treated as though they were
included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may
be used separately under those permissions, but the entire Program remains
governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when
you modify the work.) You may place additional permissions on material, added
by you to a covered work, for which you have or can give appropriate copyright
permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed
by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in reasonable
ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors or authors
of the material; or
- e) Declining to grant rights under trademark law for use of some trade
names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that material by
anyone who conveys the material (or modified versions of it) with
contractual assumptions of liability to the recipient, for any liability
that these contractual assumptions directly impose on those licensors and
authors.
All other non-permissive additional terms are considered *further restrictions*
within the meaning of section 10. If the Program as you received it, or any
part of it, contains a notice stating that it is governed by this License along
with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or
conveying under this License, you may add to a covered work material governed
by the terms of that license document, provided that the further restriction
does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place,
in the relevant source files, a statement of the additional terms that apply to
those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements
apply either way.
### 8. Termination.
You may not propagate or modify a covered work except as expressly provided
under this License. Any attempt otherwise to propagate or modify it is void,
and will automatically terminate your rights under this License (including any
patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated
- a) provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and
- b) permanently, if the copyright holder fails to notify you of the
violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated
permanently if the copyright holder notifies you of the violation by some
reasonable means, this is the first time you have received notice of violation
of this License (for any work) from that copyright holder, and you cure the
violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses
of parties who have received copies or rights from you under this License. If
your rights have been terminated and not permanently reinstated, you do not
qualify to receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy
of the Program. Ancillary propagation of a covered work occurring solely as a
consequence of using peer-to-peer transmission to receive a copy likewise does
not require acceptance. However, nothing other than this License grants you
permission to propagate or modify any covered work. These actions infringe
copyright if you do not accept this License. Therefore, by modifying or
propagating a covered work, you indicate your acceptance of this License to do
so.
### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a
license from the original licensors, to run, modify and propagate that work,
subject to this License. You are not responsible for enforcing compliance by
third parties with this License.
An *entity transaction* is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered work
results from an entity transaction, each party to that transaction who receives
a copy of the work also receives whatever licenses to the work the party's
predecessor in interest had or could give under the previous paragraph, plus a
right to possession of the Corresponding Source of the work from the
predecessor in interest, if the predecessor has it or can get it with
reasonable efforts.
You may not impose any further restrictions on the exercise of the rights
granted or affirmed under this License. For example, you may not impose a
license fee, royalty, or other charge for exercise of rights granted under this
License, and you may not initiate litigation (including a cross-claim or
counterclaim in a lawsuit) alleging that any patent claim is infringed by
making, using, selling, offering for sale, or importing the Program or any
portion of it.
### 11. Patents.
A *contributor* is a copyright holder who authorizes use under this License of
the Program or a work on which the Program is based. The work thus licensed is
called the contributor's *contributor version*.
A contributor's *essential patent claims* are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired,
that would be infringed by some manner, permitted by this License, of making,
using, or selling its contributor version, but do not include claims that would
be infringed only as a consequence of further modification of the contributor
version. For purposes of this definition, *control* includes the right to grant
patent sublicenses in a manner consistent with the requirements of this
License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent
license under the contributor's essential patent claims, to make, use, sell,
offer for sale, import and otherwise run, modify and propagate the contents of
its contributor version.
In the following three paragraphs, a *patent license* is any express agreement
or commitment, however denominated, not to enforce a patent (such as an express
permission to practice a patent or covenant not to sue for patent
infringement). To *grant* such a patent license to a party means to make such
an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of
charge and under the terms of this License, through a publicly available
network server or other readily accessible means, then you must either
1. cause the Corresponding Source to be so available, or
2. arrange to deprive yourself of the benefit of the patent license for this
particular work, or
3. arrange, in a manner consistent with the requirements of this License, to
extend the patent license to downstream recipients.
*Knowingly relying* means you have actual knowledge that, but for the patent
license, your conveying the covered work in a country, or your recipient's use
of the covered work in a country, would infringe one or more identifiable
patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a
patent license to some of the parties receiving the covered work authorizing
them to use, propagate, modify or convey a specific copy of the covered work,
then the patent license you grant is automatically extended to all recipients
of the covered work and works based on it.
A patent license is *discriminatory* if it does not include within the scope of
its coverage, prohibits the exercise of, or is conditioned on the non-exercise
of one or more of the rights that are specifically granted under this License.
You may not convey a covered work if you are a party to an arrangement with a
third party that is in the business of distributing software, under which you
make payment to the third party based on the extent of your activity of
conveying the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory patent
license
- a) in connection with copies of the covered work conveyed by you (or copies
made from those copies), or
- b) primarily for and in connection with specific products or compilations
that contain the covered work, unless you entered into that arrangement, or
that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to
you under applicable patent law.
### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not excuse
you from the conditions of this License. If you cannot convey a covered work so
as to satisfy simultaneously your obligations under this License and any other
pertinent obligations, then as a consequence you may not convey it at all. For
example, if you agree to terms that obligate you to collect a royalty for
further conveying from those to whom you convey the Program, the only way you
could satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to
link or combine any covered work with a work licensed under version 3 of the
GNU Affero General Public License into a single combined work, and to convey
the resulting work. The terms of this License will continue to apply to the
part which is the covered work, but the special requirements of the GNU Affero
General Public License, section 13, concerning interaction through a network
will apply to the combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in
spirit to the present version, but may differ in detail to address new problems
or concerns.
Each version is given a distinguishing version number. If the Program specifies
that a certain numbered version of the GNU General Public License *or any later
version* applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by
the Free Software Foundation. If the Program does not specify a version number
of the GNU General Public License, you may choose any version ever published by
the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the
GNU General Public License can be used, that proxy's public statement of
acceptance of a version permanently authorizes you to choose that version for
the Program.
Later license versions may give you additional or different permissions.
However, no additional obligations are imposed on any author or copyright
holder as a result of your choosing to follow a later version.
### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY
HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot
be given local legal effect according to their terms, reviewing courts shall
apply local law that most closely approximates an absolute waiver of all civil
liability in connection with the Program, unless a warranty or assumption of
liability accompanies a copy of the Program in return for a fee.
## END OF TERMS AND CONDITIONS ###
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible
use to the public, the best way to achieve this is to make it free software
which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach
them to the start of each source file to most effectively state the exclusion
of warranty; and each file should have at least the *copyright* line and a
pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like
this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w` and `show c` should show the appropriate
parts of the General Public License. Of course, your program's commands might
be different; for a GUI interface, you would use an *about box*.
You should also get your employer (if you work as a programmer) or school, if
any, to sign a *copyright disclaimer* for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
[http://www.gnu.org/licenses/](http://www.gnu.org/licenses/).
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider
it more useful to permit linking proprietary applications with the library. If
this is what you want to do, use the GNU Lesser General Public License instead
of this License. But first, please read
[http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html).

View File

@@ -2,36 +2,45 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Preconnect to external domains for performance -->
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
<link rel="dns-prefetch" href="https://cdnjs.cloudflare.com">
<link rel="preconnect" href="https://a.adhd.sh" crossorigin>
<link rel="dns-prefetch" href="https://a.adhd.sh">
<link rel="preconnect" href="https://pagead2.googlesyndication.com" crossorigin>
<link rel="dns-prefetch" href="https://pagead2.googlesyndication.com">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" /> <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="shortcut icon" href="/favicon.ico" /> <link rel="shortcut icon" href="/favicon.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<meta name="apple-mobile-web-app-title" content="MyWebSite" /> <meta name="apple-mobile-web-app-title" content="Spritesheet Generator" />
<link rel="manifest" href="/site.webmanifest" /> <link rel="manifest" href="/site.webmanifest" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Primary Meta Tags --> <!-- Primary Meta Tags -->
<title>Spritesheet Generator - Create Game Spritesheets Online</title> <title>Spritesheet generator - Create Game Spritesheets Online</title>
<meta name="title" content="Spritesheet Generator - Create Game Spritesheets Online"> <meta name="title" content="Spritesheet generator - Create Game Spritesheets Online">
<meta name="description" content="Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview."> <meta name="description" content="Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview.">
<meta name="keywords" content="spritesheet generator, sprite sheet maker, game development, pixel art, sprite animation, game assets, 2D game tools"> <meta name="keywords" content="Spritesheet generator, sprite sheet maker, game development, pixel art, sprite animation, game assets, 2D game tools">
<meta name="author" content="nu11ed"> <meta name="author" content="streetshadow">
<meta name="robots" content="index, follow"> <meta name="robots" content="index, follow">
<link rel="canonical" href="https://spritesheetgenerator.online/">
<!-- Open Graph / Facebook --> <!-- Open Graph / Facebook -->
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:url" content="https://spritesheetgenerator.online/"> <meta property="og:url" content="https://spritesheetgenerator.online/">
<meta property="og:title" content="Spritesheet Generator - Create Game Spritesheets Online"> <meta property="og:title" content="Spritesheet generator - Create Game Spritesheets Online">
<meta property="og:description" content="Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview."> <meta property="og:description" content="Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview.">
<meta property="og:image" content="/og-image.png"> <meta property="og:image" content="/og-image.png">
<!-- Twitter --> <!-- Twitter -->
<meta property="twitter:card" content="summary_large_image"> <meta property="twitter:card" content="summary_large_image">
<meta property="twitter:url" content="https://spritesheetgenerator.online/"> <meta property="twitter:url" content="https://spritesheetgenerator.online/">
<meta property="twitter:title" content="Spritesheet Generator - Create Game Spritesheets Online"> <meta property="twitter:title" content="Spritesheet generator - Create Game Spritesheets Online">
<meta property="twitter:description" content="Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview."> <meta property="twitter:description" content="Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview.">
<meta property="twitter:image" content="/og-image.png"> <meta property="twitter:image" content="/og-image.png">
@@ -39,8 +48,6 @@
<meta name="theme-color" content="#0096ff" media="(prefers-color-scheme: light)"> <meta name="theme-color" content="#0096ff" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#111827" media="(prefers-color-scheme: dark)"> <meta name="theme-color" content="#111827" media="(prefers-color-scheme: dark)">
<title>Spritesheet generator</title>
<script <script
src="https://a.adhd.sh/api/script.js" src="https://a.adhd.sh/api/script.js"
data-site-id="7" data-site-id="7"
@@ -48,9 +55,6 @@
data-session-replay="true" data-session-replay="true"
defer defer
></script> ></script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3715260871588949"
crossorigin="anonymous"></script>
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>

1031
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,18 +13,23 @@
}, },
"dependencies": { "dependencies": {
"@tailwindcss/vite": "^4.1.1", "@tailwindcss/vite": "^4.1.1",
"@vueuse/head": "^2.0.0",
"buffer": "^6.0.3",
"gif.js": "^0.2.0", "gif.js": "^0.2.0",
"gray-matter": "^4.0.3",
"jszip": "^3.10.1", "jszip": "^3.10.1",
"marked": "^15.0.7", "marked": "^15.0.7",
"pinia": "^3.0.1", "pinia": "^3.0.1",
"pocketbase": "^0.26.2", "pocketbase": "^0.26.2",
"vue": "^3.5.13" "vue": "^3.5.13",
"vue-router": "^4.6.3"
}, },
"devDependencies": { "devDependencies": {
"@ianvs/prettier-plugin-sort-imports": "^4.4.1", "@ianvs/prettier-plugin-sort-imports": "^4.4.1",
"@tailwindcss/typography": "^0.5.19",
"@tsconfig/node22": "^22.0.1", "@tsconfig/node22": "^22.0.1",
"@types/gif.js": "^0.2.5", "@types/gif.js": "^0.2.5",
"@types/node": "^22.13.14", "@types/node": "^22.19.1",
"@vitejs/plugin-vue": "^5.2.3", "@vitejs/plugin-vue": "^5.2.3",
"@vue/tsconfig": "^0.7.0", "@vue/tsconfig": "^0.7.0",
"autoprefixer": "^10.4.21", "autoprefixer": "^10.4.21",

View File

@@ -1,7 +1,18 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## [1.8.0] - 2025-11-23
- Fix context menu location
- You can now reposition all sprites in current frame
## [1.7.0] - 2025-11-22
- Add layer support
- Add background color picker
- Improved UI
## [1.6.0] - 2025-11-18 ## [1.6.0] - 2025-11-18
- Improved animation preview modal - Improved animation preview modal
- Add toggle for negative spacing in cells
- Show cell size
## [1.5.0] - 2025-11-17 ## [1.5.0] - 2025-11-17
- Show offset values in sprite cells and in preview modal - Show offset values in sprite cells and in preview modal
@@ -32,30 +43,30 @@ All notable changes to this project will be documented in this file.
## [1.7.0] - 2025-05-02 ## [1.7.0] - 2025-05-02
### Removed ### Removed
- 🪟 Checkerboard pattern inside sprite cells as it could conflict with the sprite. (Thanks Rivers) - Checkerboard pattern inside sprite cells as it could conflict with the sprite. (Thanks Rivers)
## [1.6.0] - 2025-04-30 ## [1.6.0] - 2025-04-30
### Added ### Added
- 🎨 Dark mode support - Dark mode support
- Preview other sprites inside cells from overview - Preview other sprites inside cells from overview
## [1.5.0] - 2025-04-30 ## [1.5.0] - 2025-04-30
### Added ### Added
- 📏 Offset indicators for better sprite alignment - Offset indicators for better sprite alignment
- Set base offset for offset indicators - Set base offset for offset indicators
## [1.4.0] - 2025-04-06 ## [1.4.0] - 2025-04-06
### Added ### Added
- 🎥 Download as GIF functionality - Download as GIF functionality
- 🗂 Download as ZIP functionality - Download as ZIP functionality
## [1.3.0] - 2025-04-06 ## [1.3.0] - 2025-04-06
### Fixed ### Fixed
- 📄 When importing a spritesheet, the tool will now remove transparent from the edges of each sprite so you can move them inside their cells. - When importing a spritesheet, the tool will now remove transparent from the edges of each sprite so you can move them inside their cells.
## [1.2.0] - 2025-04-06 ## [1.2.0] - 2025-04-06
@@ -65,22 +76,22 @@ All notable changes to this project will be documented in this file.
## [1.1.0] - 2025-04-06 ## [1.1.0] - 2025-04-06
### Added ### Added
- 📝 Help modal with instructions and tips - Help modal with instructions and tips
- 🎨 Pixel perfect mode for better sprite alignment - Pixel perfect mode for better sprite alignment
## [1.0.0] - 2025-04-06 ## [1.0.0] - 2025-04-06
### Added ### Added
- 🎉 Initial release - 🎉 Initial release
- Basic spritesheet generation functionality - Basic spritesheet generation functionality
- Drag and drop image upload - Drag and drop image upload
- Grid-based sprite arrangement - Grid-based sprite arrangement
- Custom grid size configuration - Custom grid size configuration
- 🎮 Animation preview functionality - Animation preview functionality
- Real-time animation preview - Real-time animation preview
- Adjustable animation speed - Adjustable animation speed
- Frame-by-frame navigation - Frame-by-frame navigation
- 💾 JSON import/export support - JSON import/export support
- Save sprite arrangements - Save sprite arrangements
- Load previous projects - Load previous projects
- Export configuration files - Export configuration files

1
public/ads.txt Normal file
View File

@@ -0,0 +1 @@
google.com, pub-3715260871588949, DIRECT, f08c47fec0942fa0

BIN
public/blog/1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 758 KiB

BIN
public/blog/2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

3
public/robots.txt Normal file
View File

@@ -0,0 +1,3 @@
User-agent: *
Allow: /
Sitemap: https://spritesheetgenerator.online/sitemap.xml

42
public/sitemap.xml Normal file
View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<url>
<loc>https://spritesheetgenerator.online/</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/about</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/contact</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/privacy-policy</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/blog</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/blog/why-pixel-art</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/blog/welcome</loc>
<lastmod>2025-11-26T15:50:00+00:00</lastmod>
</url>
<url>
<loc>https://spritesheetgenerator.online/faq</loc>
<lastmod>2025-11-26T19:37:00+00:00</lastmod>
</url>
</urlset>

View File

@@ -1,132 +1,67 @@
<template> <template>
<div class="min-h-screen p-3 sm:p-6 bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 transition-colors duration-300"> <div class="min-h-screen flex flex-col p-4 sm:p-8 bg-slate-50 dark:bg-gray-950 transition-colors duration-300" :class="{ 'lg:h-screen': layers.some(l => l.sprites.length) && $route.name === 'home' }">
<div class="max-w-7xl mx-auto"> <!-- Decorative gradient blur in top-right corner -->
<div class="flex flex-col sm:flex-row justify-between items-center mb-4 sm:mb-8 gap-2"> <div class="fixed top-0 right-0 w-[600px] h-[600px] bg-gradient-to-bl from-blue-400/40 via-purple-400/30 to-transparent dark:from-blue-400/30 dark:via-purple-400/20 blur-3xl pointer-events-none -translate-y-32 translate-x-32"></div>
<h1 class="text-2xl sm:text-4xl font-bold text-gray-900 dark:text-white tracking-tight text-center sm:text-left">Spritesheet generator</h1> <div class="flex flex-col flex-1" :class="{ 'lg:overflow-hidden': layers.some(l => l.sprites.length) && $route.name === 'home' }">
<header class="mb-6 sm:mb-8">
<div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-6 mb-6">
<div class="text-center sm:text-left w-full sm:w-auto">
<router-link to="/" class="block group" title="Spritesheet Generator - Create professional spritesheets" aria-label="Go to homepage">
<span class="inline-block text-3xl sm:text-4xl lg:text-5xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-gray-900 to-gray-700 dark:from-white dark:to-gray-300 tracking-tight mb-2 sm:mb-3 group-hover:opacity-80 transition-opacity">Spritesheet generator</span>
</router-link>
<p class="text-sm sm:text-base text-gray-600 dark:text-gray-400 font-medium">Create professional spritesheets for your game development projects</p>
</div>
<div class="flex flex-col items-center sm:items-end gap-3 w-full sm:w-auto">
<nav class="flex flex-wrap items-center justify-center sm:justify-end gap-2 sm:gap-3">
<a href="https://gitea.adhd.sh/root/spritesheet-generator" target="_blank" rel="noopener noreferrer" class="btn btn-secondary hover:shadow-md" data-rybbit-event="source-link" title="View source code on Gitea" aria-label="View source code repository">
<i class="fab fa-github"></i>
<span class="font-medium">Source</span>
</a>
<a href="https://discord.gg/JTev3nzeDa" target="_blank" rel="noopener noreferrer" class="btn btn-secondary hover:shadow-md" data-rybbit-event="discord-link" title="Join our Discord community" aria-label="Join Discord server">
<i class="fab fa-discord"></i>
<span class="font-medium">Discord</span>
</a>
<a href="#" @click.prevent="openHelpModal" class="btn btn-secondary hover:shadow-md" data-rybbit-event="help-link" title="Get help and documentation" aria-label="Open help modal">
<i class="fas fa-question-circle"></i>
<span class="font-medium">Help</span>
</a>
<a href="#" @click.prevent="openFeedbackModal" class="btn btn-secondary hover:shadow-md" data-rybbit-event="feedback-link" title="Share your feedback with us" aria-label="Open feedback modal">
<i class="fas fa-comment-dots"></i>
<span class="font-medium">Feedback</span>
</a>
<dark-mode-toggle /> <dark-mode-toggle />
</nav>
<div class="flex flex-wrap items-center justify-center sm:justify-end gap-3 sm:gap-4 text-xs sm:text-sm font-medium text-gray-600 dark:text-gray-400">
<router-link to="/" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="Spritesheet Generator Home" aria-label="Navigate to home page">Home</router-link>
<router-link to="/blog" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="Read our blog posts" aria-label="Navigate to blog">Blog</router-link>
<router-link to="/about" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="Learn more about us" aria-label="Navigate to about page">About Us</router-link>
<router-link to="/contact" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="Get in touch with us" aria-label="Navigate to contact page">Contact</router-link>
<router-link to="/faq" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="Frequently Asked Questions" aria-label="Navigate to FAQ page">FAQ</router-link>
<router-link to="/privacy-policy" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="Read our privacy policy" aria-label="Navigate to privacy policy">Privacy Policy</router-link>
<a href="/sitemap.xml" target="_blank" rel="noopener noreferrer" class="hover:text-gray-900 dark:hover:text-white transition-colors whitespace-nowrap" title="View XML sitemap" aria-label="View sitemap">Sitemap</a>
</div> </div>
<div class="flex flex-wrap justify-center gap-4 mb-4 sm:mb-8">
<a href="https://gitea.adhd.sh/root/spritesheet-generator" target="_blank" class="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300 transition-colors" data-rybbit-event="source-link"> <i class="fab fa-github"></i> Source </a>
<a href="https://discord.gg/JTev3nzeDa" target="_blank" class="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300 transition-colors" data-rybbit-event="discord-link"> <i class="fab fa-discord"></i> Discord </a>
<a href="#" @click.prevent="openHelpModal" class="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300 transition-colors" data-rybbit-event="help-link"> <i class="fas fa-question-circle"></i> Help </a>
<a href="#" @click.prevent="openFeedbackModal" class="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300 transition-colors" data-rybbit-event="feedback-link"> <i class="fas fa-comment-dots"></i> Feedback </a>
</div> </div>
</div>
</header>
<div class="bg-white dark:bg-gray-800 rounded-2xl shadow-soft dark:shadow-gray-900/30 p-4 sm:p-8 transition-colors duration-300"> <Breadcrumbs />
<div class="flex flex-col sm:flex-row justify-between items-center mb-4 sm:mb-6 gap-3">
<h2 class="text-xl font-semibold text-gray-800 dark:text-gray-100">Upload sprites</h2>
<button
@click="openJSONImportDialog"
class="w-full sm:w-auto px-4 py-2 bg-indigo-500 hover:bg-indigo-600 dark:bg-indigo-600 dark:hover:bg-indigo-700 text-white font-medium rounded-lg transition-colors flex items-center justify-center sm:justify-start space-x-2"
data-rybbit-event="import-json"
>
<i class="fas fa-file-import"></i>
<span>Import JSON</span>
</button>
</div>
<file-uploader @upload-sprites="handleSpritesUpload" />
<input ref="jsonFileInput" type="file" accept=".json,application/json" class="hidden" @change="handleJSONFileChange" />
<div v-if="!sprites.length" class="mt-8">
<div class="mt-2 leading-relaxed space-y-2">
<p>Create spritesheets for your game development and animation projects with our completely free, open-source spritesheet generator.</p>
<p>This powerful online tool lets you upload individual sprite images and automatically arrange them into optimized sprite sheets with customizable layouts - perfect for indie developers, animators, and studios of any size.</p>
<p class="font-bold text-2xl pb-3 pt-2">How it works:</p>
<video controls playsinline class="w-full h-full object-contain rounded-lg shadow-md" title="Spritesheet generator tutorial" aria-label="Spritesheet generator tutorial">
<source src="@/assets/tut2.mp4" type="video/mp4" />
</video>
</div>
</div>
<div v-if="sprites.length > 0" class="mt-8"> <router-view />
<div class="flex flex-wrap items-center justify-center sm:justify-start gap-3 sm:gap-6 mb-6 sm:mb-8">
<div class="flex items-center space-x-1">
<label for="columns" class="text-gray-700 dark:text-gray-200 font-medium">Columns:</label>
<input
id="columns"
type="number"
v-model.number="columns"
min="1"
max="10"
class="w-20 px-3 py-2 border border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 rounded-lg focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent outline-none transition-all text-base"
/>
</div> </div>
<!-- Add mass position buttons -->
<div class="flex flex-wrap items-center justify-center gap-2">
<button @click="alignSprites('left')" class="p-3 sm:p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-100 rounded-lg transition-colors" title="Align Left" data-rybbit-event="align-left">
<i class="fas fa-arrow-left"></i>
</button>
<button @click="alignSprites('center')" class="p-3 sm:p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-100 rounded-lg transition-colors" title="Align Center" data-rybbit-event="align-center">
<i class="fas fa-arrows-left-right"></i>
</button>
<button @click="alignSprites('right')" class="p-3 sm:p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-100 rounded-lg transition-colors" title="Align Right" data-rybbit-event="align-right">
<i class="fas fa-arrow-right"></i>
</button>
<button @click="alignSprites('top')" class="p-3 sm:p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-100 rounded-lg transition-colors" title="Align Top" data-rybbit-event="align-top">
<i class="fas fa-arrow-up"></i>
</button>
<button @click="alignSprites('middle')" class="p-3 sm:p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-100 rounded-lg transition-colors" title="Align Middle" data-rybbit-event="align-middle">
<i class="fas fa-arrows-up-down"></i>
</button>
<button @click="alignSprites('bottom')" class="p-3 sm:p-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-100 rounded-lg transition-colors" title="Align Bottom" data-rybbit-event="align-bottom">
<i class="fas fa-arrow-down"></i>
</button>
</div>
<button @click="downloadSpritesheet" class="w-full sm:w-auto px-6 py-3 sm:py-2.5 bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700 text-white font-medium rounded-lg transition-colors flex items-center justify-center space-x-2" data-rybbit-event="download-spritesheet">
<i class="fas fa-download"></i>
<span>Download spritesheet</span>
</button>
<button
@click="exportSpritesheetJSON"
class="w-full sm:w-auto px-6 py-3 sm:py-2.5 bg-purple-500 hover:bg-purple-600 dark:bg-purple-600 dark:hover:bg-purple-700 text-white font-medium rounded-lg transition-colors flex items-center justify-center space-x-2"
data-rybbit-event="export-json"
>
<i class="fas fa-file-code"></i>
<span>Export as JSON</span>
</button>
<button @click="openGifFpsModal" class="w-full sm:w-auto px-6 py-3 sm:py-2.5 bg-amber-500 hover:bg-amber-600 dark:bg-amber-600 dark:hover:bg-amber-700 text-white font-medium rounded-lg transition-colors flex items-center justify-center space-x-2" data-rybbit-event="download-gif">
<i class="fas fa-film"></i>
<span>Download as GIF</span>
</button>
<button @click="downloadAsZip" class="w-full sm:w-auto px-6 py-3 sm:py-2.5 bg-teal-500 hover:bg-teal-600 dark:bg-teal-600 dark:hover:bg-teal-700 text-white font-medium rounded-lg transition-colors flex items-center justify-center space-x-2" data-rybbit-event="download-zip">
<i class="fas fa-file-archive"></i>
<span>Download as ZIP</span>
</button>
<button @click="openPreviewModal" class="w-full sm:w-auto px-6 py-3 sm:py-2.5 bg-green-500 hover:bg-green-600 dark:bg-green-600 dark:hover:bg-green-700 text-white font-medium rounded-lg transition-colors flex items-center justify-center space-x-2" data-rybbit-event="preview-animation">
<i class="fas fa-play"></i>
<span>Preview animation</span>
</button>
</div>
<sprite-canvas :sprites="sprites" :columns="columns" @update-sprite="updateSpritePosition" @update-sprite-cell="updateSpriteCell" @remove-sprite="removeSprite" @replace-sprite="replaceSprite" @add-sprite="addSprite" @add-sprite-with-resize="addSpriteWithResize" />
</div>
</div>
</div>
<Modal :is-open="isPreviewModalOpen" @close="closePreviewModal" title="Animation preview">
<sprite-preview :sprites="sprites" :columns="columns" @update-sprite="updateSpritePosition" />
</Modal>
<HelpModal :is-open="isHelpModalOpen" @close="closeHelpModal" /> <HelpModal :is-open="isHelpModalOpen" @close="closeHelpModal" />
<FeedbackModal :is-open="isFeedbackModalOpen" @close="closeFeedbackModal" /> <FeedbackModal :is-open="isFeedbackModalOpen" @close="closeFeedbackModal" />
<SpritesheetSplitter :is-open="isSpritesheetSplitterOpen" :image-url="spritesheetImageUrl" :image-file="spritesheetImageFile" @close="closeSpritesheetSplitter" @split="handleSplitSpritesheet" />
<GifFpsModal :is-open="isGifFpsModalOpen" @close="closeGifFpsModal" @confirm="downloadAsGif" :default-fps="10" />
<!-- One-time feedback popup --> <!-- One-time feedback popup -->
<div v-if="showFeedbackPopup" class="fixed inset-0 backdrop-blur-sm flex items-center justify-center z-50"> <div v-if="showFeedbackPopup" class="fixed inset-0 z-50 flex items-center justify-center backdrop-blur-sm">
<div class="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-md mx-4 shadow-xl border border-gray-600"> <div class="max-w-md p-6 mx-4 bg-white dark:bg-gray-800 border border-gray-600 rounded-xl shadow-xl">
<div class="text-center"> <div class="text-center">
<div class="text-4xl mb-4">💬</div> <div class="mb-4 text-4xl">💬</div>
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-3">Help us improve!</h3> <h3 class="mb-3 text-lg font-semibold text-gray-900 dark:text-white">Help us improve!</h3>
<p class="text-gray-600 dark:text-gray-300 mb-6">We'd love to hear your thoughts about the spritesheet generator. Would you like to share your feedback?</p> <p class="mb-6 text-gray-600 dark:text-gray-300">We'd love to hear your thoughts about the Spritesheet generator. Would you like to share your feedback?</p>
<div class="flex gap-3 justify-center"> <div class="flex justify-center gap-3">
<button @click="handleFeedbackPopupResponse(false)" class="px-4 py-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors">Maybe later</button> <button @click="handleFeedbackPopupResponse(false)" class="px-4 py-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 transition-colors cursor-pointer">Maybe later</button>
<button @click="handleFeedbackPopupResponse(true)" class="px-6 py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors">Share feedback</button> <button @click="handleFeedbackPopupResponse(true)" class="px-6 py-2 font-medium text-white bg-gray-700 hover:bg-gray-800 rounded-lg transition-colors cursor-pointer">Share feedback</button>
</div> </div>
</div> </div>
</div> </div>
@@ -135,190 +70,20 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'; import { ref, onMounted } from 'vue';
import FileUploader from './components/FileUploader.vue'; import { RouterView, RouterLink } from 'vue-router';
import SpriteCanvas from './components/SpriteCanvas.vue';
import Modal from './components/utilities/Modal.vue';
import SpritePreview from './components/SpritePreview.vue';
import HelpModal from './components/HelpModal.vue'; import HelpModal from './components/HelpModal.vue';
import FeedbackModal from './components/FeedbackModal.vue'; import FeedbackModal from './components/FeedbackModal.vue';
import SpritesheetSplitter from './components/SpritesheetSplitter.vue';
import GifFpsModal from './components/GifFpsModal.vue';
import DarkModeToggle from './components/utilities/DarkModeToggle.vue'; import DarkModeToggle from './components/utilities/DarkModeToggle.vue';
import GIF from 'gif.js'; import Breadcrumbs from './components/Breadcrumbs.vue';
import gifWorkerUrl from 'gif.js/dist/gif.worker.js?url'; import { useLayers } from './composables/useLayers';
import JSZip from 'jszip';
interface Sprite { const { layers, hasSprites } = useLayers();
id: string;
file: File;
img: HTMLImageElement;
url: string;
width: number;
height: number;
x: number;
y: number;
}
interface SpriteFile {
file: File;
x: number;
y: number;
width: number;
height: number;
}
const sprites = ref<Sprite[]>([]);
const columns = ref(4);
// Clamp and coerce columns to a safe range [1..10]
watch(columns, val => {
const num = typeof val === 'number' ? val : parseInt(String(val));
const safe = Number.isFinite(num) && num >= 1 ? Math.min(num, 10) : 1;
if (safe !== columns.value) columns.value = safe;
});
const isPreviewModalOpen = ref(false);
const isHelpModalOpen = ref(false); const isHelpModalOpen = ref(false);
const isFeedbackModalOpen = ref(false); const isFeedbackModalOpen = ref(false);
const isSpritesheetSplitterOpen = ref(false);
const isGifFpsModalOpen = ref(false);
const jsonFileInput = ref<HTMLInputElement | null>(null);
const spritesheetImageUrl = ref('');
const spritesheetImageFile = ref<File | null>(null);
const showFeedbackPopup = ref(false); const showFeedbackPopup = ref(false);
const handleSpritesUpload = (files: File[]) => {
// Check if any of the files is a JSON file
const jsonFile = files.find(file => file.type === 'application/json' || file.name.endsWith('.json'));
if (jsonFile) {
// If it's a JSON file, try to import it
importSpritesheetJSON(jsonFile);
return;
}
// Check if it's a single image file that might be a spritesheet
if (files.length === 1 && files[0].type.startsWith('image/')) {
const file = files[0];
const url = URL.createObjectURL(file);
// Load the image to check its dimensions
const img = new Image();
img.onload = () => {
// Ask the user if they want to split the spritesheet
if (confirm('This looks like it might be a spritesheet. Would you like to split it into individual sprites?')) {
// Open the spritesheet splitter
spritesheetImageUrl.value = url;
spritesheetImageFile.value = file;
isSpritesheetSplitterOpen.value = true;
return;
}
// If the user doesn't want to split or it's not large enough, process as a single sprite
processImageFiles([file]);
};
img.src = url;
return;
}
// Process multiple image files normally
processImageFiles(files);
};
// Extract the image processing logic to a separate function for reuse
const processImageFiles = (files: File[]) => {
Promise.all(
files.map(file => {
return new Promise<Sprite>(resolve => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
resolve({
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
});
};
img.src = url;
});
})
).then(newSprites => {
sprites.value = [...sprites.value, ...newSprites];
});
};
const updateSpritePosition = (id: string, x: number, y: number) => {
const spriteIndex = sprites.value.findIndex(sprite => sprite.id === id);
if (spriteIndex !== -1) {
// Ensure integer positions for pixel-perfect rendering
sprites.value[spriteIndex].x = Math.floor(x);
sprites.value[spriteIndex].y = Math.floor(y);
}
};
const downloadSpritesheet = () => {
if (sprites.value.length === 0) {
alert('Please upload or import sprites before downloading the spritesheet.');
return;
}
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Find max dimensions
let maxWidth = 0;
let maxHeight = 0;
sprites.value.forEach(sprite => {
if (sprite.width > maxWidth) maxWidth = sprite.width;
if (sprite.height > maxHeight) maxHeight = sprite.height;
});
// Set canvas size
const rows = Math.ceil(sprites.value.length / columns.value);
canvas.width = maxWidth * columns.value;
canvas.height = maxHeight * rows;
// Disable image smoothing for pixel-perfect rendering
ctx.imageSmoothingEnabled = false;
// Draw sprites with integer positions
sprites.value.forEach((sprite, index) => {
const col = index % columns.value;
const row = Math.floor(index / columns.value);
const cellX = Math.floor(col * maxWidth);
const cellY = Math.floor(row * maxHeight);
ctx.drawImage(sprite.img, Math.floor(cellX + sprite.x), Math.floor(cellY + sprite.y));
});
// Create download link with PNG format
const link = document.createElement('a');
link.download = 'spritesheet.png';
link.href = canvas.toDataURL('image/png', 1.0); // Use maximum quality
link.click();
};
// Preview modal control
const openPreviewModal = () => {
if (sprites.value.length === 0) {
alert('Please upload or import sprites to preview an animation.');
return;
}
isPreviewModalOpen.value = true;
};
const closePreviewModal = () => {
isPreviewModalOpen.value = false;
};
// Help modal control
const openHelpModal = () => { const openHelpModal = () => {
isHelpModalOpen.value = true; isHelpModalOpen.value = true;
}; };
@@ -327,7 +92,6 @@
isHelpModalOpen.value = false; isHelpModalOpen.value = false;
}; };
// Feedback modal control
const openFeedbackModal = () => { const openFeedbackModal = () => {
isFeedbackModalOpen.value = true; isFeedbackModalOpen.value = true;
}; };
@@ -336,512 +100,15 @@
isFeedbackModalOpen.value = false; isFeedbackModalOpen.value = false;
}; };
// Spritesheet splitter modal control
const closeSpritesheetSplitter = () => {
isSpritesheetSplitterOpen.value = false;
// Clean up the URL object to prevent memory leaks
if (spritesheetImageUrl.value) {
URL.revokeObjectURL(spritesheetImageUrl.value);
spritesheetImageUrl.value = '';
}
spritesheetImageFile.value = null;
};
// GIF FPS modal control
const openGifFpsModal = () => {
if (sprites.value.length === 0) {
alert('Please upload or import sprites before generating a GIF.');
return;
}
isGifFpsModalOpen.value = true;
};
const closeGifFpsModal = () => {
isGifFpsModalOpen.value = false;
};
// Handle the split spritesheet result
const handleSplitSpritesheet = (spriteFiles: SpriteFile[]) => {
// Process sprite files with their positions
Promise.all(
spriteFiles.map(spriteFile => {
return new Promise<Sprite>(resolve => {
const url = URL.createObjectURL(spriteFile.file);
const img = new Image();
img.onload = () => {
resolve({
id: crypto.randomUUID(),
file: spriteFile.file,
img,
url,
width: img.width,
height: img.height,
x: 0, // Start at top-left of cell; ignore splitter bounding-box offset for display
y: 0, // Start at top-left of cell; ignore splitter bounding-box offset for display
});
};
img.src = url;
});
})
).then(newSprites => {
sprites.value = [...sprites.value, ...newSprites];
});
};
// Export spritesheet as JSON with base64 images
const exportSpritesheetJSON = async () => {
if (sprites.value.length === 0) {
alert('Nothing to export. Please add sprites first.');
return;
}
// Create an array to store sprite data with base64 images
const spritesData = await Promise.all(
sprites.value.map(async (sprite, index) => {
// Create a canvas for each sprite to get its base64 data
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return null;
// Set canvas size to match the sprite
canvas.width = sprite.width;
canvas.height = sprite.height;
// Draw the sprite
ctx.drawImage(sprite.img, 0, 0);
// Get base64 data
const base64Data = canvas.toDataURL('image/png');
return {
id: sprite.id,
width: sprite.width,
height: sprite.height,
x: sprite.x,
y: sprite.y,
base64: base64Data,
name: sprite.file.name,
};
})
);
// Create JSON object with all necessary data
const jsonData = {
columns: columns.value,
sprites: spritesData.filter(Boolean), // Remove any null values
};
// Convert to JSON string
const jsonString = JSON.stringify(jsonData, null, 2);
// Create download link
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'spritesheet.json';
link.href = url;
link.click();
// Clean up
URL.revokeObjectURL(url);
};
// Open file dialog for JSON import
const openJSONImportDialog = () => {
jsonFileInput.value?.click();
};
// Handle JSON file selection
const handleJSONFileChange = (event: Event) => {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
const jsonFile = input.files[0];
importSpritesheetJSON(jsonFile);
// Reset input value so uploading the same file again will trigger the event
if (jsonFileInput.value) jsonFileInput.value.value = '';
}
};
// Import spritesheet from JSON
const importSpritesheetJSON = async (jsonFile: File) => {
try {
const jsonText = await jsonFile.text();
const jsonData = JSON.parse(jsonText);
if (!jsonData.sprites || !Array.isArray(jsonData.sprites)) {
throw new Error('Invalid JSON format: missing sprites array');
}
// Set columns if available
if (jsonData.columns && typeof jsonData.columns === 'number') {
columns.value = jsonData.columns;
}
// Process each sprite
// Replace current sprites with imported ones
// Revoke existing blob: URLs to avoid memory leaks
if (sprites.value.length) {
sprites.value.forEach(s => {
if (s.url && s.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(s.url);
} catch {}
}
});
}
sprites.value = await Promise.all(
jsonData.sprites.map(async (spriteData: any) => {
return new Promise<Sprite>(resolve => {
// Create image from base64
const img = new Image();
img.onload = () => {
// Create a file from the base64 data
const byteString = atob(spriteData.base64.split(',')[1]);
const mimeType = spriteData.base64.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
const blob = new Blob([ab], { type: mimeType });
const fileName = spriteData.name || `sprite-${spriteData.id}.png`;
const file = new File([blob], fileName, { type: mimeType });
resolve({
id: spriteData.id || crypto.randomUUID(),
file,
img,
url: spriteData.base64,
width: spriteData.width,
height: spriteData.height,
x: spriteData.x || 0,
y: spriteData.y || 0,
});
};
img.src = spriteData.base64;
});
})
);
} catch (error) {
console.error('Error importing JSON:', error);
alert('Failed to import JSON file. Please check the file format.');
}
};
// Add new alignment function
const alignSprites = (position: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom') => {
if (sprites.value.length === 0) return;
// Find max dimensions for the current column layout
let maxWidth = 0;
let maxHeight = 0;
sprites.value.forEach(sprite => {
maxWidth = Math.max(maxWidth, sprite.width);
maxHeight = Math.max(maxHeight, sprite.height);
});
sprites.value = sprites.value.map((sprite, index) => {
let x = sprite.x;
let y = sprite.y;
switch (position) {
case 'left':
x = 0;
break;
case 'center':
x = Math.floor((maxWidth - sprite.width) / 2);
break;
case 'right':
x = Math.floor(maxWidth - sprite.width);
break;
case 'top':
y = 0;
break;
case 'middle':
y = Math.floor((maxHeight - sprite.height) / 2);
break;
case 'bottom':
y = Math.floor(maxHeight - sprite.height);
break;
}
// Ensure integer positions for pixel-perfect rendering
return { ...sprite, x: Math.floor(x), y: Math.floor(y) };
});
// Force redraw of the preview canvas
setTimeout(() => {
const event = new Event('forceRedraw');
window.dispatchEvent(event);
}, 0);
};
const updateSpriteCell = (id: string, newIndex: number) => {
// Find the current index of the sprite
const currentIndex = sprites.value.findIndex(sprite => sprite.id === id);
if (currentIndex === -1) return;
// If we're trying to move to the same position, do nothing
if (currentIndex === newIndex) return;
// Create a copy of the sprites array
const newSprites = [...sprites.value];
// Perform a swap between the two positions
if (newIndex < sprites.value.length) {
// Get references to both sprites
const movingSprite = { ...newSprites[currentIndex] };
const targetSprite = { ...newSprites[newIndex] };
// Swap them
newSprites[currentIndex] = targetSprite;
newSprites[newIndex] = movingSprite;
} else {
// If dragging to an empty cell (beyond the array length)
// Use the original reordering logic
const [movedSprite] = newSprites.splice(currentIndex, 1);
newSprites.splice(newIndex, 0, movedSprite);
}
// Update the sprites array
sprites.value = newSprites;
};
const removeSprite = (id: string) => {
const spriteIndex = sprites.value.findIndex(sprite => sprite.id === id);
if (spriteIndex !== -1) {
const sprite = sprites.value[spriteIndex];
// Revoke the blob URL to prevent memory leaks
if (sprite.url && sprite.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(sprite.url);
} catch {}
}
// Remove the sprite from the array
sprites.value.splice(spriteIndex, 1);
}
};
const replaceSprite = (id: string, file: File) => {
const spriteIndex = sprites.value.findIndex(sprite => sprite.id === id);
if (spriteIndex !== -1) {
const oldSprite = sprites.value[spriteIndex];
// Revoke the old blob URL to prevent memory leaks
if (oldSprite.url && oldSprite.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(oldSprite.url);
} catch {}
}
// Create new sprite from the replacement file
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
const newSprite: Sprite = {
id: oldSprite.id, // Keep the same ID
file,
img,
url,
width: img.width,
height: img.height,
x: oldSprite.x, // Keep the same position
y: oldSprite.y,
};
// Create a new array to trigger Vue's reactivity
const newSprites = [...sprites.value];
newSprites[spriteIndex] = newSprite;
sprites.value = newSprites;
};
img.onerror = () => {
console.error('Failed to load replacement image:', file.name);
URL.revokeObjectURL(url);
};
img.src = url;
}
};
const addSprite = (file: File) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
const newSprite: Sprite = {
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
};
sprites.value = [...sprites.value, newSprite];
};
img.onerror = () => {
console.error('Failed to load new sprite image:', file.name);
URL.revokeObjectURL(url);
};
img.src = url;
};
const addSpriteWithResize = (file: File) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
// Find current max dimensions
let maxWidth = 0;
let maxHeight = 0;
sprites.value.forEach(sprite => {
maxWidth = Math.max(maxWidth, sprite.width);
maxHeight = Math.max(maxHeight, sprite.height);
});
// Create new sprite
const newSprite: Sprite = {
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
};
// Calculate new max dimensions after adding the new sprite
const newMaxWidth = Math.max(maxWidth, img.width);
const newMaxHeight = Math.max(maxHeight, img.height);
// Resize existing sprites if the new image is larger
if (img.width > maxWidth || img.height > maxHeight) {
// Update all existing sprites to center them in the new larger cells
sprites.value = sprites.value.map(sprite => {
let newX = sprite.x;
let newY = sprite.y;
// Adjust x position if width increased
if (img.width > maxWidth) {
const widthDiff = newMaxWidth - maxWidth;
// Try to keep the sprite in the same relative position
const relativeX = maxWidth > 0 ? sprite.x / maxWidth : 0;
newX = Math.floor(relativeX * newMaxWidth);
// Make sure it doesn't go out of bounds
newX = Math.max(0, Math.min(newX, newMaxWidth - sprite.width));
}
// Adjust y position if height increased
if (img.height > maxHeight) {
const heightDiff = newMaxHeight - maxHeight;
const relativeY = maxHeight > 0 ? sprite.y / maxHeight : 0;
newY = Math.floor(relativeY * newMaxHeight);
newY = Math.max(0, Math.min(newY, newMaxHeight - sprite.height));
}
return { ...sprite, x: newX, y: newY };
});
}
// Add the new sprite
sprites.value = [...sprites.value, newSprite];
// Force redraw of the canvas
setTimeout(() => {
const event = new Event('forceRedraw');
window.dispatchEvent(event);
}, 0);
};
img.onerror = () => {
console.error('Failed to load new sprite image:', file.name);
URL.revokeObjectURL(url);
};
img.src = url;
};
// Download as GIF with specified FPS
const downloadAsGif = (fps: number) => {
if (sprites.value.length === 0) {
alert('Please upload or import sprites before generating a GIF.');
return;
}
// Find max dimensions
let maxWidth = 0;
let maxHeight = 0;
sprites.value.forEach(sprite => {
if (sprite.width > maxWidth) maxWidth = sprite.width;
if (sprite.height > maxHeight) maxHeight = sprite.height;
});
// Create a canvas for rendering frames
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Set canvas size to just fit one sprite cell
canvas.width = maxWidth;
canvas.height = maxHeight;
// Disable image smoothing for pixel-perfect rendering
ctx.imageSmoothingEnabled = false;
// Create GIF encoder
const gif = new GIF({
workers: 2,
quality: 10,
width: maxWidth,
height: maxHeight,
workerScript: gifWorkerUrl,
});
// Add each sprite as a frame
sprites.value.forEach(sprite => {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw grid background (cell)
ctx.fillStyle = '#f9fafb';
ctx.fillRect(0, 0, maxWidth, maxHeight);
// Draw sprite
ctx.drawImage(sprite.img, Math.floor(sprite.x), Math.floor(sprite.y));
// Add frame to GIF
gif.addFrame(ctx, { copy: true, delay: 1000 / fps });
});
// Generate GIF
gif.on('finished', (blob: Blob) => {
// Create download link
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'animation.gif';
link.href = url;
link.click();
// Clean up
URL.revokeObjectURL(url);
});
gif.render();
};
// Check for one-time feedback popup on mount
onMounted(() => { onMounted(() => {
const hasShownFeedbackPopup = localStorage.getItem('hasShownFeedbackPopup'); const hasShownFeedbackPopup = localStorage.getItem('hasShownFeedbackPopup');
if (!hasShownFeedbackPopup) { if (!hasShownFeedbackPopup) {
// Show popup after a short delay to let the page load
setTimeout(() => { setTimeout(() => {
showFeedbackPopup.value = true; showFeedbackPopup.value = true;
}, 3000); }, 3000);
} }
}); });
// Handle feedback popup response
const handleFeedbackPopupResponse = (showModal: boolean) => { const handleFeedbackPopupResponse = (showModal: boolean) => {
showFeedbackPopup.value = false; showFeedbackPopup.value = false;
localStorage.setItem('hasShownFeedbackPopup', 'true'); localStorage.setItem('hasShownFeedbackPopup', 'true');
@@ -850,90 +117,4 @@
openFeedbackModal(); openFeedbackModal();
} }
}; };
// Revoke blob URLs on unmount to avoid memory leaks
onUnmounted(() => {
sprites.value.forEach(s => {
if (s.url && s.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(s.url);
} catch {}
}
});
});
// Download as ZIP with each cell individually
const downloadAsZip = async () => {
if (sprites.value.length === 0) {
alert('Please upload or import sprites before downloading a ZIP.');
return;
}
// Create a new ZIP file
const zip = new JSZip();
// Find max dimensions
let maxWidth = 0;
let maxHeight = 0;
sprites.value.forEach(sprite => {
if (sprite.width > maxWidth) maxWidth = sprite.width;
if (sprite.height > maxHeight) maxHeight = sprite.height;
});
// Create a canvas for rendering individual sprites
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Set canvas size to just fit one sprite cell
canvas.width = maxWidth;
canvas.height = maxHeight;
// Disable image smoothing for pixel-perfect rendering
ctx.imageSmoothingEnabled = false;
// Add each sprite as an individual file
sprites.value.forEach((sprite, index) => {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw grid background (cell)
ctx.fillStyle = '#f9fafb';
ctx.fillRect(0, 0, maxWidth, maxHeight);
// Draw sprite
ctx.drawImage(sprite.img, Math.floor(sprite.x), Math.floor(sprite.y));
// Convert to PNG data URL
const dataURL = canvas.toDataURL('image/png');
// Convert data URL to binary data
const binaryData = atob(dataURL.split(',')[1]);
const arrayBuffer = new ArrayBuffer(binaryData.length);
const uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < binaryData.length; i++) {
uint8Array[i] = binaryData.charCodeAt(i);
}
// Add to ZIP file with clearer naming
const baseName = sprite.file?.name ? sprite.file.name.replace(/\s+/g, '_') : `sprite_${index + 1}.png`;
const name = `${index + 1}_${baseName}`;
zip.file(name, uint8Array);
});
// Generate ZIP file
const content = await zip.generateAsync({ type: 'blob' });
// Create download link
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.download = 'sprites.zip';
link.href = url;
link.click();
// Clean up
URL.revokeObjectURL(url);
};
</script> </script>

BIN
src/assets/demo.mp4 Normal file

Binary file not shown.

View File

@@ -4,9 +4,6 @@
/* Dark mode transition */ /* Dark mode transition */
html, html,
body { body {
transition:
background-color 0.3s ease,
color 0.3s ease;
-webkit-tap-highlight-color: transparent; /* Remove tap highlight on mobile */ -webkit-tap-highlight-color: transparent; /* Remove tap highlight on mobile */
} }
@@ -37,3 +34,142 @@ html.dark {
touch-action: manipulation; /* Improve touch responsiveness */ touch-action: manipulation; /* Improve touch responsiveness */
} }
} }
@layer components {
.btn {
@apply inline-flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg transition-all cursor-pointer font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed active:scale-95;
}
.btn-primary {
@apply bg-gray-900 text-white hover:bg-gray-800 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-200;
}
.btn-secondary {
@apply bg-white text-gray-700 border border-gray-200 hover:bg-gray-50 hover:shadow-sm dark:bg-gray-800 dark:text-gray-200 dark:border-gray-700 dark:hover:bg-gray-700;
}
.btn-ghost {
@apply text-gray-600 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800;
}
.btn-danger {
@apply text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/30;
}
.btn-dark {
@apply bg-gray-700 text-white hover:bg-gray-800 dark:bg-gray-600 dark:hover:bg-gray-700;
}
.btn-sm {
@apply px-3 py-1.5 text-xs;
}
.btn-md {
@apply px-4 py-2 text-sm;
}
.btn-icon {
@apply p-2;
}
.btn-icon-sm {
@apply p-1.5;
}
.btn-icon-xs {
@apply p-1;
}
.input-field {
@apply px-2 py-1 text-sm border border-gray-300 rounded outline-none focus:ring-2 focus:ring-gray-500 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100;
}
.card {
@apply bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg;
}
/* Custom prose styles for blog content */
.prose {
@apply text-gray-700 dark:text-gray-300 leading-7;
}
.prose h1 {
@apply text-4xl font-bold text-gray-900 dark:text-white mb-4 mt-0;
}
.prose h2 {
@apply text-3xl font-bold text-gray-900 dark:text-white mt-8 mb-4;
}
.prose h3 {
@apply text-2xl font-bold text-gray-900 dark:text-white mt-6 mb-3;
}
.prose h4 {
@apply text-xl font-bold text-gray-900 dark:text-white mt-4 mb-2;
}
.prose p {
@apply text-gray-700 dark:text-gray-300 mb-4 leading-7;
}
.prose a {
@apply text-blue-600 dark:text-blue-400 underline hover:text-blue-800 dark:hover:text-blue-300;
}
.prose strong {
@apply text-gray-900 dark:text-white font-semibold;
}
.prose em {
@apply italic;
}
.prose code {
@apply text-sm font-mono bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100 px-1 py-0.5 rounded;
}
.prose pre {
@apply bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-200 p-4 rounded-lg overflow-x-auto mb-4;
}
.prose pre code {
@apply bg-transparent p-0;
}
.prose ul {
@apply list-disc pl-6 mb-4 text-gray-700 dark:text-gray-300;
}
.prose ol {
@apply list-decimal pl-6 mb-4 text-gray-700 dark:text-gray-300;
}
.prose li {
@apply mb-2 leading-7;
}
.prose blockquote {
@apply border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic text-gray-600 dark:text-gray-400 my-4;
}
.prose img {
@apply rounded-lg shadow-md my-6;
}
.prose hr {
@apply border-gray-300 dark:border-gray-700 my-8;
}
.prose table {
@apply border-collapse w-full my-6;
}
.prose th {
@apply bg-gray-100 dark:bg-gray-800 p-2 text-left font-semibold border border-gray-300 dark:border-gray-700;
}
.prose td {
@apply border border-gray-300 dark:border-gray-700 p-2;
}
}

23
src/blog/welcome.md Normal file
View File

@@ -0,0 +1,23 @@
---
title: 'Welcome to the Spritesheet generator blog'
date: '2025-11-26'
description: 'This is the first post on our new blog. Learn about how we built this tool.'
image: '/blog/1.png'
---
## Welcome!
We are excited to launch our new blog. Here we will share updates, tutorials, and tips on how to get the most out of the Sprite Sheet Generator.
### What is this tool?
This tool allows you to easily combine multiple images into a single sprite sheet. It's perfect for game developers and web designers.
### Features
- Drag and drop interface
- Customizable grid size
- Export to PNG and JSON
- Dark mode support
Stay tuned for more updates!

97
src/blog/why-pixel-art.md Normal file
View File

@@ -0,0 +1,97 @@
---
title: 'Why pixel art without proper spritesheet tools is holding you back'
date: '2025-11-26'
description: 'Pixel art is already challenging. Why make it harder?'
image: '/blog/2.jpg'
---
If you've worked on game projects with pixel art, you know the pain: managing dozens of individual sprite files, keeping track of animation frames, and organizing everything into a format your game engine can use. It's tedious, error-prone, and kills your creative flow.
## The pixel art workflow nightmare
### The zoom dance problem
Pixel artists constantly switch between magnified and unmagnified views. At 500% zoom, you place individual pixels. At 100%, you check if they create the intended effect. You need to see both the micro details and the macro picture—but you can't do both at once.
This back-and-forth is exhausting, especially when you discover a single shade-too-dark pixel throws off your entire composition.
### File management chaos
Creating a character with idle, walking, running, jumping, and attacking animations? Each with 8-12 frames? That's 40-60+ individual image files for one character.
Managing these manually means:
- Tracking which file belongs to which animation
- Ensuring consistent sizing across all frames
- Organizing files in the right sequence
- Exporting each frame separately
- Hoping you didn't skip or misname anything
### The multi-tool trap
Many developers juggle multiple applications:
1. Sketch in a drawing program
2. Refine in a pixel art editor
3. Export individual frames
4. Resize in an image editor
5. Manually arrange in another tool
6. Export as a spritesheet
7. Create data files for your game engine
8. Find an error in frame 23
9. Start over
One developer described the frustration: the feedback loop was too long. They couldn't see what the finished art would look like until after going through multiple tools. Details that looked great in high-res turned sloppy after conversion.
## Why spritesheets matter
Sprite sheets aren't optional—they're essential for game development:
- **Better performance**: One file instead of 50+ individual image requests
- **Simpler management**: One file instead of dozens
- **Proper animation**: Frame data embedded or easily referenced
- **Optimized memory**: Better texture packing, less wasted space
But creating them manually is painful. You need to calculate optimal layouts, ensure consistent spacing, maintain pixel-perfect alignment, and generate metadata. One mistake breaks your animations.
## The solution: dedicated spritesheet generators
This is where [spritesheetgenerator.online](https://spritesheetgenerator.online) changes everything.
Instead of the multi-tool nightmare, you get:
1. **Upload sprites**: Drag and drop your images
2. **Automatic arrangement**: Intelligent optimal layout
3. **Preview animations**: See your work in real-time
4. **Export everything**: Spritesheet image and data files ready to use
### Why this matters
**Faster iteration**: Change frame 7? Re-upload and regenerate in seconds instead of minutes.
**Consistent results**: No more alignment worries. The tool handles technical details.
**Immediate preview**: See frames flow together, check light-blending in motion, verify timing—all before exporting.
**Professional output**: Properly formatted spritesheets that drop right into your game engine.
### Free and accessible
Being browser-based means:
- No installation required
- Works on any device
- No subscriptions or licenses
- Access from anywhere
For indie developers, hobbyists, or students with limited budgets, this is game-changing.
## The bottom line
Pixel art requires precision and patience. That's part of what makes it rewarding. But there's no reason to add unnecessary complexity with manual file management and multi-tool workflows.
Your creative energy should go into placing pixels with intention and crafting smooth animations—not file wrangling.
Using a proper spritesheet generator doesn't make you less of an artist. It makes you a smarter one.
The pixel art is hard enough. The workflow doesn't have to be.

View File

@@ -0,0 +1,63 @@
<script setup lang="ts">
import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { RouterLink } from 'vue-router';
const route = useRoute();
interface BreadcrumbItem {
name: string;
path: string;
}
const breadcrumbs = computed<BreadcrumbItem[]>(() => {
const items: BreadcrumbItem[] = [{ name: 'Home', path: '/' }];
// Map route names to breadcrumb labels
const routeLabels: Record<string, string> = {
'blog-overview': 'Blog',
'blog-detail': 'Blog',
about: 'About Us',
contact: 'Contact',
'privacy-policy': 'Privacy Policy',
faq: 'FAQ',
};
if (route.name && route.name !== 'home') {
const routeName = route.name.toString();
if (routeName === 'blog-detail') {
// For blog detail pages, add Blog first, then the post title
items.push({ name: 'Blog', path: '/blog' });
// Get the post title from route meta or params if available
const postTitle = (route.meta.title as string) || 'Article';
items.push({ name: postTitle, path: route.path });
} else if (routeLabels[routeName]) {
items.push({ name: routeLabels[routeName], path: route.path });
}
}
return items;
});
const shouldShowBreadcrumbs = computed(() => {
return breadcrumbs.value.length > 1 && route.name !== 'home';
});
</script>
<template>
<nav v-if="shouldShowBreadcrumbs" aria-label="Breadcrumb" class="mb-4">
<ol class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
<li v-for="(item, index) in breadcrumbs" :key="item.path" class="flex items-center gap-2">
<RouterLink v-if="index < breadcrumbs.length - 1" :to="item.path" class="hover:text-gray-900 dark:hover:text-white transition-colors" :aria-label="`Navigate to ${item.name}`">
{{ item.name }}
</RouterLink>
<span v-else class="font-medium text-gray-900 dark:text-white" aria-current="page">
{{ item.name }}
</span>
<i v-if="index < breadcrumbs.length - 1" class="fas fa-chevron-right text-xs text-gray-400"></i>
</li>
</ol>
</nav>
</template>

View File

@@ -1,9 +1,9 @@
<template> <template>
<div <div
class="border-2 border-dashed rounded-xl p-4 sm:p-8 text-center transition-all duration-200" class="relative border-3 border-dashed rounded-2xl p-8 sm:p-12 text-center transition-all duration-300 cursor-pointer group overflow-hidden"
:class="{ :class="{
'border-blue-300 bg-blue-50 dark:border-blue-500 dark:bg-blue-900/30': isDragging, 'border-blue-400 bg-blue-50 dark:border-blue-400 dark:bg-blue-900/40 scale-[1.02]': isDragging,
'border-gray-200 hover:border-blue-300 hover:bg-gray-50 dark:border-gray-600 dark:hover:border-blue-500 dark:hover:bg-gray-700/50': !isDragging, 'border-gray-300 bg-gray-50/50 hover:border-blue-400 hover:bg-blue-50/80 dark:border-gray-600 dark:bg-gray-800/30 dark:hover:border-blue-400 dark:hover:bg-blue-900/30': !isDragging,
}" }"
@dragenter.prevent="isDragging = true" @dragenter.prevent="isDragging = true"
@dragleave.prevent="isDragging = false" @dragleave.prevent="isDragging = false"
@@ -12,20 +12,36 @@
@click="openFileDialog" @click="openFileDialog"
data-rybbit-event="file-upload-area" data-rybbit-event="file-upload-area"
> >
<div class="absolute inset-0 bg-blue-400/0 group-hover:bg-blue-400/5 transition-all duration-300"></div>
<input ref="fileInput" type="file" multiple accept="image/*,.json" class="hidden" @change="handleFileChange" /> <input ref="fileInput" type="file" multiple accept="image/*,.json" class="hidden" @change="handleFileChange" />
<div class="mb-4 sm:mb-6"> <div class="relative z-10">
<img src="@/assets/images/file.svg" alt="File upload" class="w-16 h-16 sm:w-20 sm:h-20 mx-auto mb-2 sm:mb-4 opacity-75 dark:invert" /> <div class="mb-6 transform transition-transform duration-300" :class="isDragging ? 'scale-110' : 'group-hover:scale-105'">
<div class="w-20 h-20 sm:w-24 sm:h-24 mx-auto mb-4 bg-blue-100 dark:bg-blue-900/50 rounded-2xl flex items-center justify-center shadow-lg">
<i class="fas fa-cloud-upload-alt text-4xl sm:text-5xl text-blue-600 dark:text-blue-400"></i>
</div>
</div> </div>
<p class="text-lg sm:text-xl font-medium text-gray-700 dark:text-gray-200 mb-2">Drag and drop your sprite images or JSON file here</p> <h3 class="text-xl sm:text-2xl font-bold text-gray-800 dark:text-gray-100 mb-3">
<p class="text-sm text-gray-500 dark:text-gray-400 mb-4 sm:mb-6">or</p> <span v-if="isDragging">Drop your files here</span>
<span v-else>Upload Your Sprites</span>
</h3>
<p class="text-base sm:text-lg text-gray-600 dark:text-gray-300 mb-2">Drag and drop sprite images or JSON files</p>
<p class="text-sm text-gray-500 dark:text-gray-400 mb-8">Supports PNG, JPG, GIF, and JSON</p>
<button class="w-full sm:w-auto px-6 py-3 sm:py-2.5 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg transition-colors flex sm:inline-flex items-center justify-center space-x-2 cursor-pointer" data-rybbit-event="select-files"> <div class="flex items-center justify-center gap-4 mb-6">
<i class="fas fa-folder-open"></i> <div class="h-px flex-1 bg-gray-300 dark:bg-gray-600"></div>
<span>Select files</span> <span class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">or</span>
<div class="h-px flex-1 bg-gray-300 dark:bg-gray-600"></div>
</div>
<button class="px-8 py-3.5 bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700 text-white font-semibold rounded-xl shadow-lg hover:shadow-xl transition-all transform hover:scale-105 flex items-center justify-center gap-3 mx-auto" data-rybbit-event="select-files">
<i class="fas fa-folder-open text-lg"></i>
<span>Browse Files</span>
</button> </button>
</div> </div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">

View File

@@ -23,7 +23,7 @@
<div class="max-w-none text-gray-700 dark:text-gray-300"> <div class="max-w-none text-gray-700 dark:text-gray-300">
<p class="mb-4 text-base leading-relaxed">Spritesheet generator is a free, open-source tool for creating spritesheets for game development and animation projects. This tool allows you to upload individual sprite images and arrange them into a spritesheet with customizable layout.</p> <p class="mb-4 text-base leading-relaxed">Spritesheet generator is a free, open-source tool for creating spritesheets for game development and animation projects. This tool allows you to upload individual sprite images and arrange them into a spritesheet with customizable layout.</p>
<p class="mb-4 text-base leading-relaxed">Matrix: root@adhd.sh, Discord: nu11ed</p> <p class="mb-4 text-base leading-relaxed">Matrix: root@adhd.sh, Discord: streetshadow</p>
<h4 class="mt-6 mb-3 text-lg font-medium text-gray-900 dark:text-gray-100">How to use:</h4> <h4 class="mt-6 mb-3 text-lg font-medium text-gray-900 dark:text-gray-100">How to use:</h4>
<ol class="list-decimal pl-6 space-y-2 mb-4"> <ol class="list-decimal pl-6 space-y-2 mb-4">
<li>Upload your sprite images by dragging and dropping them or clicking the upload area</li> <li>Upload your sprite images by dragging and dropping them or clicking the upload area</li>
@@ -56,6 +56,16 @@
</p> </p>
<div class="space-y-6"> <div class="space-y-6">
<!-- Ko-fi -->
<div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
<div class="flex items-center mb-3">
<h4 class="text-md font-medium">Ko-fi</h4>
</div>
<a href="https://ko-fi.com/X8X416D44P" target="_blank" rel="noopener noreferrer" data-rybbit-event="open-kofi">
<img height="36" style="border: 0px; height: 36px" src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" alt="Buy Me a Coffee at ko-fi.com" />
</a>
</div>
<!-- PayPal --> <!-- PayPal -->
<div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"> <div class="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
<div class="flex items-center mb-3"> <div class="flex items-center mb-3">

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +1,74 @@
<template> <template>
<div class="spritesheet-preview w-full"> <div class="spritesheet-preview w-full h-full">
<!-- Main Layout: Canvas Left, Controls Right --> <div class="flex flex-col lg:flex-row gap-4 h-full">
<div class="flex flex-col lg:flex-row gap-4"> <div class="flex-1 min-w-0 flex flex-col">
<!-- Canvas Area (Left/Main) --> <div
<div class="flex-1 min-w-0"> class="relative bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg overflow-auto flex-1 min-h-[300px] max-h-[calc(100vh-12rem)] shadow-sm hover:shadow-md transition-shadow duration-200"
<div class="relative bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg overflow-auto min-h-[300px] sm:min-h-[520px] shadow-sm hover:shadow-md transition-shadow duration-200">
<canvas
ref="previewCanvasRef"
@mousedown="startDrag"
@mousemove="drag" @mousemove="drag"
@mouseup="stopDrag" @mouseup="stopDrag"
@mouseleave="stopDrag" @mouseleave="stopDrag"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove" @touchmove="handleTouchMove"
@touchend="stopDrag" @touchend="stopDrag"
class="block touch-manipulation"
:class="{ 'cursor-move': isDraggable }"
:style="{ transform: `scale(${zoom})`, transformOrigin: 'top left', ...(settingsStore.pixelPerfect ? { 'image-rendering': 'pixelated' } : {}) }"
> >
</canvas> <div
ref="previewContainerRef"
class="relative touch-manipulation inline-block"
:style="{
transform: `scale(${zoom})`,
transformOrigin: 'top left',
width: `${cellDimensions.cellWidth}px`,
height: `${cellDimensions.cellHeight}px`,
backgroundColor: '#f9fafb',
backgroundImage: getPreviewBackgroundImage(),
backgroundSize: settingsStore.backgroundColor === 'transparent' ? '20px 20px' : 'auto',
backgroundPosition: settingsStore.backgroundColor === 'transparent' ? '0 0, 0 10px, 10px -10px, -10px 0px' : '0 0',
border: `1px solid ${settingsStore.darkMode ? '#4b5563' : '#e5e7eb'}`,
}"
>
<!-- Background sprites (dimmed for comparison) -->
<template v-if="showAllSprites">
<template v-for="i in maxFrames()" :key="`bg-${i - 1}`">
<template v-if="i - 1 !== currentFrameIndex && !hiddenFrames.includes(i - 1)">
<template v-for="layer in getVisibleLayers()" :key="`${layer.id}-${i - 1}`">
<img
v-if="layer.sprites[i - 1]"
:src="layer.sprites[i - 1].url"
class="absolute pointer-events-none"
:style="{
left: `${cellDimensions.negativeSpacing + layer.sprites[i - 1].x}px`,
top: `${cellDimensions.negativeSpacing + layer.sprites[i - 1].y}px`,
width: `${layer.sprites[i - 1].width}px`,
height: `${layer.sprites[i - 1].height}px`,
opacity: '0.3',
imageRendering: settingsStore.pixelPerfect ? 'pixelated' : 'auto',
}"
draggable="false"
/>
</template>
</template>
</template>
</template>
<!-- Current frame sprites -->
<template v-for="layer in getVisibleLayers()" :key="layer.id">
<img
v-if="layer.sprites[currentFrameIndex]"
:src="layer.sprites[currentFrameIndex].url"
class="absolute"
:class="{ 'cursor-move': isDraggable }"
:style="{
left: `${cellDimensions.negativeSpacing + layer.sprites[currentFrameIndex].x}px`,
top: `${cellDimensions.negativeSpacing + layer.sprites[currentFrameIndex].y}px`,
width: `${layer.sprites[currentFrameIndex].width}px`,
height: `${layer.sprites[currentFrameIndex].height}px`,
imageRendering: settingsStore.pixelPerfect ? 'pixelated' : 'auto',
}"
@mousedown="startDrag($event, layer.sprites[currentFrameIndex], layer.id)"
@touchstart="handleTouchStart($event, layer.sprites[currentFrameIndex], layer.id)"
draggable="false"
/>
</template>
</div>
<!-- Mobile zoom controls --> <!-- Mobile zoom controls -->
<div class="absolute bottom-3 right-3 flex space-x-2 lg:hidden bg-white/80 dark:bg-gray-800/80 p-2 rounded-lg shadow-md"> <div class="absolute bottom-3 right-3 flex space-x-2 lg:hidden bg-white/80 dark:bg-gray-800/80 p-2 rounded-lg shadow-md">
@@ -32,119 +82,140 @@
</div> </div>
</div> </div>
<!-- Controls Sidebar (Right) -->
<div class="lg:w-80 xl:w-96 flex-shrink-0"> <div class="lg:w-80 xl:w-96 flex-shrink-0">
<div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 space-y-4"> <div class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 shadow-sm overflow-hidden">
<!-- Playback Controls --> <!-- Playback Controls -->
<div class="space-y-3"> <div class="p-4 border-b border-gray-100 dark:border-gray-700">
<h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide">Playback</h3> <h3 class="text-xs font-bold text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-3">Playback</h3>
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<button @click="togglePlayback" class="flex items-center justify-center gap-1.5 bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors cursor-pointer flex-1"> <button @click="togglePlayback" class="flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2.5 rounded-lg transition-all cursor-pointer flex-1 shadow-sm active:scale-95">
<span v-if="isPlaying" class="flex items-center gap-1.5"> <span v-if="isPlaying" class="flex items-center gap-2 font-medium">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5"> <i class="fas fa-pause"></i>
<path fill-rule="evenodd" d="M6.75 5.25a.75.75 0 01.75-.75H9a.75.75 0 01.75.75v13.5a.75.75 0 01-.75.75H7.5a.75.75 0 01-.75-.75V5.25zm7.5 0A.75.75 0 0115 4.5h1.5a.75.75 0 01.75.75v13.5a.75.75 0 01-.75.75H15a.75.75 0 01-.75-.75V5.25z" clip-rule="evenodd" />
</svg>
Pause Pause
</span> </span>
<span v-else class="flex items-center gap-1.5"> <span v-else class="flex items-center gap-2 font-medium">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5"> <i class="fas fa-play"></i>
<path fill-rule="evenodd" d="M4.5 5.653c0-1.426 1.529-2.33 2.779-1.643l11.54 6.348c1.295.712 1.295 2.573 0 3.285L7.28 19.991c-1.25.687-2.779-.217-2.779-1.643V5.653z" clip-rule="evenodd" />
</svg>
Play Play
</span> </span>
</button> </button>
<button @click="previousFrame" class="bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 p-2 rounded-md transition-colors duration-200 cursor-pointer" :disabled="isPlaying" :class="{ 'opacity-50 cursor-not-allowed': isPlaying }"> <button @click="previousFrame" class="btn btn-secondary btn-icon rounded-lg" :disabled="isPlaying" :class="{ 'opacity-50 cursor-not-allowed': isPlaying }">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 dark:text-gray-200"> <i class="fas fa-step-backward"></i>
<path fill-rule="evenodd" d="M11.78 5.22a.75.75 0 01.75.75v12.06l4.72-4.72a.75.75 0 111.06 1.06l-6 6a.75.75 0 01-1.06 0l-6-6a.75.75 0 011.06-1.06l4.72 4.72V5.97a.75.75 0 01.75-.75z" clip-rule="evenodd" transform="rotate(90 12 12)" />
</svg>
</button> </button>
<button @click="nextFrame" class="bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 p-2 rounded-md transition-colors duration-200 cursor-pointer" :disabled="isPlaying" :class="{ 'opacity-50 cursor-not-allowed': isPlaying }"> <button @click="nextFrame" class="btn btn-secondary btn-icon rounded-lg" :disabled="isPlaying" :class="{ 'opacity-50 cursor-not-allowed': isPlaying }">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 dark:text-gray-200"> <i class="fas fa-step-forward"></i>
<path fill-rule="evenodd" d="M11.78 5.22a.75.75 0 01.75.75v12.06l4.72-4.72a.75.75 0 111.06 1.06l-6 6a.75.75 0 01-1.06 0l-6-6a.75.75 0 011.06-1.06l4.72 4.72V5.97a.75.75 0 01.75-.75z" clip-rule="evenodd" transform="rotate(-90 12 12)" />
</svg>
</button> </button>
</div> </div>
</div> </div>
<!-- Sliders --> <!-- Animation Settings -->
<div class="space-y-3"> <div class="p-4 border-b border-gray-100 dark:border-gray-700 space-y-5">
<h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide">Controls</h3> <h3 class="text-xs font-bold text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-1">Animation</h3>
<!-- Frame Navigation --> <!-- Frame Navigation -->
<div class="space-y-1"> <div class="space-y-2">
<div class="flex justify-between items-center"> <div class="flex justify-between items-center">
<span class="text-xs font-medium text-gray-600 dark:text-gray-400">Frame</span> <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Frame</span>
<span class="text-xs font-mono text-gray-700 dark:text-gray-300">{{ visibleFrameNumber }}/{{ visibleFramesCount }}</span> <span class="text-xs font-mono text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded">{{ visibleFrameNumber }} / {{ visibleFramesCount }}</span>
</div> </div>
<input type="range" min="0" :max="visibleFrames.length - 1" :value="visibleFrameIndex" @input="handleSliderInput" class="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-500" :disabled="isPlaying" :class="{ 'opacity-50': isPlaying }" /> <input type="range" min="0" :max="visibleFrames.length - 1" :value="visibleFrameIndex" @input="handleSliderInput" class="w-full h-1.5 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-600" :disabled="isPlaying" :class="{ 'opacity-50': isPlaying }" />
</div> </div>
<!-- FPS Control --> <!-- FPS Control -->
<div class="space-y-1"> <div class="space-y-2">
<div class="flex justify-between items-center"> <div class="flex justify-between items-center">
<span class="text-xs font-medium text-gray-600 dark:text-gray-400">FPS</span> <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Speed (FPS)</span>
<span class="text-xs font-mono text-gray-700 dark:text-gray-300">{{ fps }}</span> <span class="text-xs font-mono text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded">{{ fps }}</span>
</div> </div>
<input type="range" min="1" max="60" v-model.number="fps" class="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-500" /> <input type="range" min="1" max="60" v-model.number="fps" class="w-full h-1.5 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-600" />
</div> </div>
</div>
<!-- View Options -->
<div class="p-4 space-y-5">
<h3 class="text-xs font-bold text-gray-400 dark:text-gray-500 uppercase tracking-wider mb-1">View Options</h3>
<!-- Zoom Control --> <!-- Zoom Control -->
<div class="space-y-1">
<div class="flex justify-between items-center">
<span class="text-xs font-medium text-gray-600 dark:text-gray-400">Zoom</span>
<span class="text-xs font-mono text-gray-700 dark:text-gray-300">{{ Math.round(zoom * 100) }}%</span>
</div>
<input type="range" min="0.5" max="5" step="0.1" v-model.number="zoom" class="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-500" />
</div>
</div>
<!-- Options -->
<div class="space-y-3">
<h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide">Options</h3>
<div class="space-y-2"> <div class="space-y-2">
<label class="flex items-center gap-2 cursor-pointer"> <div class="flex justify-between items-center">
<input type="checkbox" v-model="isDraggable" class="w-4 h-4 text-blue-500 focus:ring-blue-400 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700" /> <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Zoom</span>
<span class="text-sm dark:text-gray-200">Reposition</span> <span class="text-xs font-mono text-gray-500 dark:text-gray-400 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded">{{ Math.round(zoom * 100) }}%</span>
</div>
<input type="range" min="0.5" max="5" step="0.1" v-model.number="zoom" class="w-full h-1.5 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-600" />
</div>
<!-- Toggles -->
<div class="space-y-3 pt-2">
<label class="flex items-center justify-between cursor-pointer group">
<span class="text-sm text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-gray-100 transition-colors">Pixel perfect</span>
<div class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="settingsStore.pixelPerfect" class="sr-only peer" />
<div
class="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"
></div>
</div>
</label> </label>
<label class="flex items-center gap-2 cursor-pointer"> <label class="flex items-center justify-between cursor-pointer group">
<input type="checkbox" v-model="showAllSprites" class="w-4 h-4 text-blue-500 focus:ring-blue-400 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700" /> <span class="text-sm text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-gray-100 transition-colors">Reposition mode</span>
<span class="text-sm dark:text-gray-200">Compare sprites</span> <div class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="isDraggable" class="sr-only peer" />
<div
class="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"
></div>
</div>
</label> </label>
<label class="flex items-center gap-2 cursor-pointer"> <div class="pl-4 border-l-2 border-gray-100 dark:border-gray-700 transition-all" :class="{ 'opacity-50 pointer-events-none': !isDraggable }">
<input type="checkbox" v-model="settingsStore.pixelPerfect" class="w-4 h-4 text-blue-500 focus:ring-blue-400 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700" @change="drawPreviewCanvas" /> <label class="flex items-center justify-between cursor-pointer group">
<span class="text-sm dark:text-gray-200">Pixel perfect</span> <span class="text-sm text-gray-600 dark:text-gray-400 group-hover:text-gray-800 dark:group-hover:text-gray-200 transition-colors">Apply to all layers</span>
<input type="checkbox" v-model="repositionAllLayers" class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600" :disabled="!isDraggable" />
</label>
</div>
<label class="flex items-center justify-between cursor-pointer group">
<span class="text-sm text-gray-700 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-gray-100 transition-colors">Compare sprites</span>
<div class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="showAllSprites" class="sr-only peer" />
<div
class="w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"
></div>
</div>
</label> </label>
</div> </div>
</div> </div>
<!-- Current frame offset display --> <!-- Current frame offset display -->
<div v-if="props.sprites[currentFrameIndex]" class="p-2 bg-gray-100 dark:bg-gray-700 rounded-md border border-gray-200 dark:border-gray-600"> <div v-if="currentFrameSprite" class="px-4 pb-4">
<div class="flex items-center justify-between"> <div class="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg border border-gray-100 dark:border-gray-700 flex items-center justify-between">
<span class="text-xs font-medium text-gray-600 dark:text-gray-400">Offset</span> <span class="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wide">Offset</span>
<span class="text-xs font-mono font-semibold text-cyan-600 dark:text-cyan-400">x: {{ props.sprites[currentFrameIndex].x }}, y: {{ props.sprites[currentFrameIndex].y }}</span> <span class="text-xs font-mono font-bold text-gray-700 dark:text-gray-200">X: {{ currentFrameSprite.x }} <span class="text-gray-300 dark:text-gray-600 mx-1">|</span> Y: {{ currentFrameSprite.y }}</span>
</div> </div>
</div> </div>
<!-- Frame Selection (when Compare sprites is enabled) --> <!-- Frame Selection (when Compare sprites is enabled) -->
<div v-if="showAllSprites" class="space-y-2"> <div v-if="showAllSprites" class="border-t border-gray-100 dark:border-gray-700 p-4">
<div class="flex items-center justify-between"> <div class="flex items-center justify-between mb-3">
<h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 uppercase tracking-wide">Frames</h3> <h3 class="text-xs font-bold text-gray-400 dark:text-gray-500 uppercase tracking-wider">Visible Frames</h3>
<div class="flex gap-1"> <div class="flex gap-1">
<button @click="showAllFrames" class="px-2 py-1 text-xs bg-blue-500 hover:bg-blue-600 text-white rounded transition-colors">All</button> <button @click="showAllFrames" class="px-2 py-1 text-[10px] font-medium bg-blue-50 text-blue-600 hover:bg-blue-100 dark:bg-blue-900/30 dark:text-blue-300 dark:hover:bg-blue-900/50 rounded transition-colors">All</button>
<button @click="hideAllFrames" class="px-2 py-1 text-xs bg-gray-500 hover:bg-gray-600 text-white rounded transition-colors">None</button> <button @click="hideAllFrames" class="px-2 py-1 text-[10px] font-medium bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600 rounded transition-colors">None</button>
</div> </div>
</div> </div>
<div class="rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-800"> <div class="bg-gray-50 dark:bg-gray-900/50 rounded-lg border border-gray-200 dark:border-gray-700 p-2">
<div class="max-h-[180px] overflow-y-auto"> <div class="max-h-[150px] overflow-y-auto pr-1 custom-scrollbar">
<div class="space-y-0.5 p-1"> <div class="space-y-1">
<div v-for="(sprite, index) in props.sprites" :key="sprite.id" class="flex items-center gap-2 px-2 py-1.5 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer rounded" @click="toggleHiddenFrame(index)"> <div v-for="(sprite, index) in compositeFrames" :key="sprite.id" class="flex items-center gap-3 px-2 py-1.5 hover:bg-white dark:hover:bg-gray-700 cursor-pointer rounded-md transition-colors group" @click="toggleHiddenFrame(index)">
<input type="checkbox" :checked="!hiddenFrames.includes(index)" class="w-3.5 h-3.5 text-blue-500 focus:ring-blue-400 rounded border-gray-300 dark:border-gray-600 dark:bg-gray-700" @click.stop @change="toggleHiddenFrame(index)" /> <input
<div class="w-8 h-8 bg-gray-100 dark:bg-gray-700 rounded flex items-center justify-center overflow-hidden flex-shrink-0"> type="checkbox"
<img :src="sprite.img.src" class="max-w-full max-h-full object-contain" :style="settingsStore.pixelPerfect ? { 'image-rendering': 'pixelated' } : {}" /> :checked="!hiddenFrames.includes(index)"
class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
@click.stop
@change="toggleHiddenFrame(index)"
/>
<div class="w-8 h-8 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 rounded flex items-center justify-center overflow-hidden flex-shrink-0 shadow-sm">
<img :src="sprite.url" class="max-w-full max-h-full object-contain" :style="settingsStore.pixelPerfect ? { 'image-rendering': 'pixelated' } : {}" />
</div> </div>
<span class="text-xs dark:text-gray-200">{{ index + 1 }}</span> <span class="text-xs font-mono text-gray-600 dark:text-gray-300 group-hover:text-gray-900 dark:group-hover:text-gray-100">Frame {{ index + 1 }}</span>
</div> </div>
</div> </div>
</div> </div>
@@ -159,196 +230,152 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, computed } from 'vue'; import { ref, onMounted, watch, onUnmounted, computed } from 'vue';
import { useSettingsStore } from '@/stores/useSettingsStore'; import { useSettingsStore } from '@/stores/useSettingsStore';
import type { Layer, Sprite } from '@/types/sprites';
interface Sprite { import { getMaxDimensionsAcrossLayers } from '@/composables/useLayers';
id: string; import { useZoom } from '@/composables/useZoom';
img: HTMLImageElement; import { useAnimationFrames } from '@/composables/useAnimationFrames';
width: number; import { calculateNegativeSpacing } from '@/composables/useNegativeSpacing';
height: number;
x: number;
y: number;
}
const props = defineProps<{ const props = defineProps<{
sprites: Sprite[]; layers: Layer[];
activeLayerId: string;
columns: number; columns: number;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'updateSprite', id: string, x: number, y: number): void; (e: 'updateSprite', id: string, x: number, y: number): void;
(e: 'updateSpriteInLayer', layerId: string, spriteId: string, x: number, y: number): void;
}>(); }>();
const previewCanvasRef = ref<HTMLCanvasElement | null>(null); const previewContainerRef = ref<HTMLDivElement | null>(null);
const ctx = ref<CanvasRenderingContext2D | null>(null);
// Preview state
const currentFrameIndex = ref(0);
const isPlaying = ref(false);
const fps = ref(12);
const zoom = ref(1);
const isDraggable = ref(false);
const showAllSprites = ref(false);
const animationFrameId = ref<number | null>(null);
const lastFrameTime = ref(0);
// Dragging state
const isDragging = ref(false);
const activeSpriteId = ref<string | null>(null);
const dragStartX = ref(0);
const dragStartY = ref(0);
const spritePosBeforeDrag = ref({ x: 0, y: 0 });
// Add this after other refs
const hiddenFrames = ref<number[]>([]);
// Get settings from store // Get settings from store
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();
// Add these computed properties const {
const visibleFrames = computed(() => props.sprites.filter((_, index) => !hiddenFrames.value.includes(index))); zoom,
const visibleFramesCount = computed(() => visibleFrames.value.length); increase: increaseZoom,
const visibleFrameIndex = computed(() => { decrease: decreaseZoom,
return visibleFrames.value.findIndex((_, idx) => idx === visibleFrames.value.findIndex(s => s === props.sprites[currentFrameIndex.value])); } = useZoom({
}); allowedValues: [0.5, 1, 2, 3, 4, 5],
const visibleFrameNumber = computed(() => visibleFrameIndex.value + 1); initial: 1,
// Canvas drawing
const calculateMaxDimensions = () => {
let maxWidth = 0;
let maxHeight = 0;
props.sprites.forEach(sprite => {
maxWidth = Math.max(maxWidth, sprite.width);
maxHeight = Math.max(maxHeight, sprite.height);
}); });
return { maxWidth, maxHeight }; const getVisibleLayers = () => props.layers.filter(l => l.visible);
}; const maxFrames = () => Math.max(0, ...getVisibleLayers().map(l => l.sprites.length));
const drawPreviewCanvas = () => { const { currentFrameIndex, isPlaying, fps, hiddenFrames, visibleFrames, visibleFramesCount, visibleFrameIndex, visibleFrameNumber, togglePlayback, nextFrame, previousFrame, handleSliderInput, toggleHiddenFrame, showAllFrames, hideAllFrames, stopAnimation } = useAnimationFrames({
if (!previewCanvasRef.value || !ctx.value || props.sprites.length === 0) return; sprites: () => {
const len = maxFrames();
const currentSprite = props.sprites[currentFrameIndex.value]; const frames: Sprite[] = [];
if (!currentSprite) return; for (let i = 0; i < len; i++) {
const s = getVisibleLayers().find(l => l.sprites[i])?.sprites[i];
const { maxWidth, maxHeight } = calculateMaxDimensions(); if (s) frames.push(s);
// Apply pixel art optimization consistently from store
ctx.value.imageSmoothingEnabled = !settingsStore.pixelPerfect;
// Set canvas size to just fit one sprite cell
previewCanvasRef.value.width = maxWidth;
previewCanvasRef.value.height = maxHeight;
// Clear canvas
ctx.value.clearRect(0, 0, previewCanvasRef.value.width, previewCanvasRef.value.height);
// Draw grid background (cell)
ctx.value.fillStyle = '#f9fafb';
ctx.value.fillRect(0, 0, maxWidth, maxHeight);
// Keep pixel art optimization consistent throughout all drawing operations
ctx.value.imageSmoothingEnabled = !settingsStore.pixelPerfect;
// Draw all sprites with transparency if enabled
if (showAllSprites.value && props.sprites.length > 1) {
ctx.value.globalAlpha = 0.3;
props.sprites.forEach((sprite, index) => {
if (index !== currentFrameIndex.value && !hiddenFrames.value.includes(index)) {
// Use Math.floor for pixel-perfect positioning
ctx.value?.drawImage(sprite.img, Math.floor(sprite.x), Math.floor(sprite.y));
} }
return frames;
},
onDraw: () => {}, // No longer needed for canvas drawing
}); });
ctx.value.globalAlpha = 1.0;
// Preview state
const isDraggable = ref(false);
const repositionAllLayers = ref(false);
const showAllSprites = ref(false);
const compositeFrames = computed<Sprite[]>(() => {
// Show frames from the active layer for the thumbnail list
const activeLayer = props.layers.find(l => l.id === props.activeLayerId);
if (!activeLayer) {
// Fallback to first visible layer if no active layer
const v = getVisibleLayers();
const len = maxFrames();
const arr: Sprite[] = [];
for (let i = 0; i < len; i++) {
const s = v.find(l => l.sprites[i])?.sprites[i];
if (s) arr.push(s);
}
return arr;
}
return activeLayer.sprites;
});
const currentFrameSprite = computed<Sprite | null>(() => {
const layer = props.layers.find(l => l.id === props.activeLayerId);
if (!layer) return null;
return layer.sprites[currentFrameIndex.value] || null;
});
// Computed cell dimensions
const cellDimensions = computed(() => {
const visibleLayers = getVisibleLayers();
// If manual cell size is enabled, use manual values
if (settingsStore.manualCellSizeEnabled) {
return {
cellWidth: settingsStore.manualCellWidth,
cellHeight: settingsStore.manualCellHeight,
negativeSpacing: 0,
};
} }
// Draw current sprite with integer positions for pixel-perfect rendering // Otherwise, calculate from sprite dimensions
ctx.value.drawImage(currentSprite.img, Math.floor(currentSprite.x), Math.floor(currentSprite.y)); const { maxWidth, maxHeight } = getMaxDimensionsAcrossLayers(visibleLayers);
const allSprites = visibleLayers.flatMap(l => l.sprites);
// Draw cell border const negativeSpacing = calculateNegativeSpacing(allSprites, settingsStore.negativeSpacingEnabled);
ctx.value.strokeStyle = '#e5e7eb'; return {
ctx.value.lineWidth = 1; cellWidth: maxWidth + negativeSpacing,
ctx.value.strokeRect(0, 0, maxWidth, maxHeight); cellHeight: maxHeight + negativeSpacing,
negativeSpacing,
}; };
});
// Animation control // Helper for background image (dark mode friendly)
const togglePlayback = () => { const getPreviewBackgroundImage = () => {
isPlaying.value = !isPlaying.value; if (settingsStore.backgroundColor === 'transparent' && settingsStore.checkerboardEnabled) {
const color = settingsStore.darkMode ? '#4b5563' : '#d1d5db';
if (isPlaying.value) { return `linear-gradient(45deg, ${color} 25%, transparent 25%), linear-gradient(-45deg, ${color} 25%, transparent 25%), linear-gradient(45deg, transparent 75%, ${color} 75%), linear-gradient(-45deg, transparent 75%, ${color} 75%)`;
startAnimation();
} else {
stopAnimation();
} }
return 'none';
}; };
const startAnimation = () => { // Dragging state
lastFrameTime.value = performance.now(); const isDragging = ref(false);
animateFrame(); const activeSpriteId = ref<string | null>(null);
}; const activeLayerId = ref<string | null>(null);
const dragStartX = ref(0);
const stopAnimation = () => { const dragStartY = ref(0);
if (animationFrameId.value !== null) { const spritePosBeforeDrag = ref({ x: 0, y: 0 });
cancelAnimationFrame(animationFrameId.value); const allSpritesPosBeforeDrag = ref<Map<string, { x: number; y: number }>>(new Map());
animationFrameId.value = null;
}
};
const animateFrame = () => {
const now = performance.now();
const elapsed = now - lastFrameTime.value;
const frameTime = 1000 / fps.value;
if (elapsed >= frameTime) {
lastFrameTime.value = now - (elapsed % frameTime);
nextFrame();
}
animationFrameId.value = requestAnimationFrame(animateFrame);
};
const nextFrame = () => {
if (visibleFrames.value.length === 0) return;
const currentVisibleIndex = visibleFrameIndex.value;
const nextVisibleIndex = (currentVisibleIndex + 1) % visibleFrames.value.length;
currentFrameIndex.value = props.sprites.indexOf(visibleFrames.value[nextVisibleIndex]);
drawPreviewCanvas();
};
const previousFrame = () => {
if (visibleFrames.value.length === 0) return;
const currentVisibleIndex = visibleFrameIndex.value;
const prevVisibleIndex = (currentVisibleIndex - 1 + visibleFrames.value.length) % visibleFrames.value.length;
currentFrameIndex.value = props.sprites.indexOf(visibleFrames.value[prevVisibleIndex]);
drawPreviewCanvas();
};
// Add this method to handle slider input
const handleSliderInput = (event: Event) => {
const target = event.target as HTMLInputElement;
const index = parseInt(target.value);
currentFrameIndex.value = props.sprites.indexOf(visibleFrames.value[index]);
};
// Drag functionality // Drag functionality
const startDrag = (event: MouseEvent) => { const startDrag = (event: MouseEvent, sprite: Sprite, layerId: string) => {
if (!isDraggable.value || !previewCanvasRef.value) return; if (!isDraggable.value || !previewContainerRef.value) return;
const rect = previewCanvasRef.value.getBoundingClientRect(); const rect = previewContainerRef.value.getBoundingClientRect();
const scaleX = previewCanvasRef.value.width / (rect.width / zoom.value); const scaleX = previewContainerRef.value.offsetWidth / (rect.width / zoom.value);
const scaleY = previewCanvasRef.value.height / (rect.height / zoom.value); const scaleY = previewContainerRef.value.offsetHeight / (rect.height / zoom.value);
const mouseX = ((event.clientX - rect.left) / zoom.value) * scaleX; const mouseX = ((event.clientX - rect.left) / zoom.value) * scaleX;
const mouseY = ((event.clientY - rect.top) / zoom.value) * scaleY; const mouseY = ((event.clientY - rect.top) / zoom.value) * scaleY;
const sprite = props.sprites[currentFrameIndex.value]; if (repositionAllLayers.value) {
isDragging.value = true;
activeSpriteId.value = 'ALL_LAYERS'; // Special marker for all layers
dragStartX.value = mouseX;
dragStartY.value = mouseY;
// Check if click is on sprite // Store initial positions for all sprites in this frame from all visible layers
if (sprite && mouseX >= sprite.x && mouseX <= sprite.x + sprite.width && mouseY >= sprite.y && mouseY <= sprite.y + sprite.height) { allSpritesPosBeforeDrag.value.clear();
const visibleLayers = getVisibleLayers();
visibleLayers.forEach(layer => {
const s = layer.sprites[currentFrameIndex.value];
if (s) {
allSpritesPosBeforeDrag.value.set(s.id, { x: s.x, y: s.y });
}
});
} else {
isDragging.value = true; isDragging.value = true;
activeSpriteId.value = sprite.id; activeSpriteId.value = sprite.id;
activeLayerId.value = layerId;
dragStartX.value = mouseX; dragStartX.value = mouseX;
dragStartY.value = mouseY; dragStartY.value = mouseY;
spritePosBeforeDrag.value = { x: sprite.x, y: sprite.y }; spritePosBeforeDrag.value = { x: sprite.x, y: sprite.y };
@@ -356,11 +383,11 @@
}; };
const drag = (event: MouseEvent) => { const drag = (event: MouseEvent) => {
if (!isDragging.value || !activeSpriteId.value || !previewCanvasRef.value) return; if (!isDragging.value || !activeSpriteId.value || !previewContainerRef.value) return;
const rect = previewCanvasRef.value.getBoundingClientRect(); const rect = previewContainerRef.value.getBoundingClientRect();
const scaleX = previewCanvasRef.value.width / (rect.width / zoom.value); const scaleX = previewContainerRef.value.offsetWidth / (rect.width / zoom.value);
const scaleY = previewCanvasRef.value.height / (rect.height / zoom.value); const scaleY = previewContainerRef.value.offsetHeight / (rect.height / zoom.value);
const mouseX = ((event.clientX - rect.left) / zoom.value) * scaleX; const mouseX = ((event.clientX - rect.left) / zoom.value) * scaleX;
const mouseY = ((event.clientY - rect.top) / zoom.value) * scaleY; const mouseY = ((event.clientY - rect.top) / zoom.value) * scaleY;
@@ -368,46 +395,52 @@
const deltaX = Math.round(mouseX - dragStartX.value); const deltaX = Math.round(mouseX - dragStartX.value);
const deltaY = Math.round(mouseY - dragStartY.value); const deltaY = Math.round(mouseY - dragStartY.value);
const sprite = props.sprites[currentFrameIndex.value]; const { cellWidth, cellHeight, negativeSpacing } = cellDimensions.value;
if (!sprite || sprite.id !== activeSpriteId.value) return;
const { maxWidth, maxHeight } = calculateMaxDimensions(); if (activeSpriteId.value === 'ALL_LAYERS') {
// Move all sprites in current frame from all visible layers
const visibleLayers = getVisibleLayers();
visibleLayers.forEach(layer => {
const sprite = layer.sprites[currentFrameIndex.value];
if (!sprite) return;
const originalPos = allSpritesPosBeforeDrag.value.get(sprite.id);
if (!originalPos) return;
// Calculate new position with constraints
let newX = Math.round(originalPos.x + deltaX);
let newY = Math.round(originalPos.y + deltaY);
// Constrain movement within expanded cell
newX = Math.max(-negativeSpacing, Math.min(cellWidth - negativeSpacing - sprite.width, newX));
newY = Math.max(-negativeSpacing, Math.min(cellHeight - negativeSpacing - sprite.height, newY));
emit('updateSpriteInLayer', layer.id, sprite.id, newX, newY);
});
} else {
// Move only the active layer sprite
const activeSprite = props.layers.find(l => l.id === activeLayerId.value)?.sprites[currentFrameIndex.value];
if (!activeSprite || activeSprite.id !== activeSpriteId.value) return;
// Calculate new position with constraints and round to integers // Calculate new position with constraints and round to integers
let newX = Math.round(spritePosBeforeDrag.value.x + deltaX); let newX = Math.round(spritePosBeforeDrag.value.x + deltaX);
let newY = Math.round(spritePosBeforeDrag.value.y + deltaY); let newY = Math.round(spritePosBeforeDrag.value.y + deltaY);
// Constrain movement within cell // Constrain movement within expanded cell (allow negative values up to -negativeSpacing)
newX = Math.max(0, Math.min(maxWidth - sprite.width, newX)); newX = Math.max(-negativeSpacing, Math.min(cellWidth - negativeSpacing - activeSprite.width, newX));
newY = Math.max(0, Math.min(maxHeight - sprite.height, newY)); newY = Math.max(-negativeSpacing, Math.min(cellHeight - negativeSpacing - activeSprite.height, newY));
emit('updateSprite', activeSpriteId.value, newX, newY); emit('updateSprite', activeSpriteId.value, newX, newY);
drawPreviewCanvas(); }
}; };
const stopDrag = () => { const stopDrag = () => {
isDragging.value = false; isDragging.value = false;
activeSpriteId.value = null; activeSpriteId.value = null;
activeLayerId.value = null;
}; };
// Add helper methods for mobile zoom controls const handleTouchStart = (event: TouchEvent, sprite: Sprite, layerId: string) => {
const increaseZoom = () => {
const zoomValues = [0.5, 1, 2, 3, 4];
const currentIndex = zoomValues.indexOf(Number(zoom.value));
if (currentIndex < zoomValues.length - 1) {
zoom.value = zoomValues[currentIndex + 1];
}
};
const decreaseZoom = () => {
const zoomValues = [0.5, 1, 2, 3, 4];
const currentIndex = zoomValues.indexOf(Number(zoom.value));
if (currentIndex > 0) {
zoom.value = zoomValues[currentIndex - 1];
}
};
const handleTouchStart = (event: TouchEvent) => {
if (!isDraggable.value) return; if (!isDraggable.value) return;
if (event.touches.length === 1) { if (event.touches.length === 1) {
@@ -416,7 +449,7 @@
clientX: touch.clientX, clientX: touch.clientX,
clientY: touch.clientY, clientY: touch.clientY,
}); });
startDrag(mouseEvent); startDrag(mouseEvent, sprite, layerId);
} }
}; };
@@ -439,84 +472,25 @@
// Lifecycle hooks // Lifecycle hooks
onMounted(() => { onMounted(() => {
if (previewCanvasRef.value) { // No longer need to initialize canvas or draw
ctx.value = previewCanvasRef.value.getContext('2d');
drawPreviewCanvas();
}
// Listen for forceRedraw event from App.vue
window.addEventListener('forceRedraw', handleForceRedraw);
}); });
onUnmounted(() => { onUnmounted(() => {
stopAnimation(); stopAnimation();
window.removeEventListener('forceRedraw', handleForceRedraw);
}); });
// Handler for force redraw event // Watchers - most canvas-related watchers removed
const handleForceRedraw = () => { // Keep layer watchers to ensure reactivity
// Ensure we're using integer positions for pixel-perfect rendering watch(
props.sprites.forEach(sprite => { () => props.layers,
sprite.x = Math.floor(sprite.x); () => {},
sprite.y = Math.floor(sprite.y); { deep: true }
}); );
watch(
// Force a redraw with the correct image smoothing settings () => props.activeLayerId,
if (ctx.value) { () => {}
ctx.value.imageSmoothingEnabled = !settingsStore.pixelPerfect; );
drawPreviewCanvas(); watch(currentFrameIndex, () => {});
}
};
// Watchers
watch(() => props.sprites, drawPreviewCanvas, { deep: true });
watch(currentFrameIndex, drawPreviewCanvas);
watch(zoom, drawPreviewCanvas);
watch(isDraggable, drawPreviewCanvas);
watch(showAllSprites, drawPreviewCanvas);
watch(hiddenFrames, drawPreviewCanvas);
watch(() => settingsStore.pixelPerfect, drawPreviewCanvas);
// Initial draw
if (props.sprites.length > 0) {
drawPreviewCanvas();
}
const toggleHiddenFrame = (index: number) => {
const currentIndex = hiddenFrames.value.indexOf(index);
if (currentIndex === -1) {
// Adding to hidden frames
hiddenFrames.value.push(index);
// If we're hiding the current frame, switch to the next visible frame
if (index === currentFrameIndex.value) {
const nextVisibleSprite = props.sprites.findIndex((_, i) => i !== index && !hiddenFrames.value.includes(i));
if (nextVisibleSprite !== -1) {
currentFrameIndex.value = nextVisibleSprite;
}
}
} else {
// Removing from hidden frames
hiddenFrames.value.splice(currentIndex, 1);
}
// Force a redraw
drawPreviewCanvas();
};
const showAllFrames = () => {
hiddenFrames.value = [];
drawPreviewCanvas();
};
const hideAllFrames = () => {
hiddenFrames.value = props.sprites.map((_, index) => index);
// Keep at least one frame visible
if (hiddenFrames.value.length > 0) {
hiddenFrames.value.splice(currentFrameIndex.value, 1);
}
drawPreviewCanvas();
};
</script> </script>
<style scoped> <style scoped>

View File

@@ -96,6 +96,7 @@
import { ref, watch, onUnmounted } from 'vue'; import { ref, watch, onUnmounted } from 'vue';
import Modal from './utilities/Modal.vue'; import Modal from './utilities/Modal.vue';
import { useSettingsStore } from '@/stores/useSettingsStore'; import { useSettingsStore } from '@/stores/useSettingsStore';
import type { SpriteFile } from '@/types/sprites';
interface SpritePreview { interface SpritePreview {
url: string; url: string;
@@ -117,14 +118,6 @@
(e: 'split', sprites: SpriteFile[]): void; // Change from File[] to SpriteFile[] (e: 'split', sprites: SpriteFile[]): void; // Change from File[] to SpriteFile[]
}>(); }>();
interface SpriteFile {
file: File;
x: number;
y: number;
width: number;
height: number;
}
// Get settings from store // Get settings from store
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();

View File

@@ -1,7 +1,5 @@
<template> <template>
<button @click="settingsStore.toggleDarkMode()" class="p-2 rounded-lg transition-colors" :class="settingsStore.darkMode ? 'text-yellow-400 hover:bg-gray-700' : 'text-gray-700 hover:bg-gray-100'" aria-label="Toggle dark mode" data-rybbit-event="toggle-dark-mode"> <button @click="settingsStore.toggleDarkMode()" class="btn btn-secondary mr-1" aria-label="Toggle dark mode" data-rybbit-event="toggle-dark-mode"><i :class="settingsStore.darkMode ? 'fas fa-sun' : 'fas fa-moon'"></i> Theme</button>
<i :class="settingsStore.darkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>
</button>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">

View File

@@ -34,7 +34,7 @@
<!-- Resize handle --> <!-- Resize handle -->
<div v-if="!isFullScreen && !isMobile" class="absolute bottom-0 right-0 w-8 h-8 cursor-se-resize" @mousedown="startResize" @touchstart="startResize"> <div v-if="!isFullScreen && !isMobile" class="absolute bottom-0 right-0 w-8 h-8 cursor-se-resize" @mousedown="startResize" @touchstart="startResize">
<svg class="w-8 h-8 text-gray-400 dark:text-gray-500" viewBox="0 0 24 24" fill="currentColor"> <svg class="w-8 h-8 text-gray-400 dark:text-gray-500" viewBox="0 0 24 24" fill="currentColor">
<path d="M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22Z"/> <path d="M22 22H20V20H22V22ZM22 18H20V16H22V18ZM18 22H16V20H18V22ZM22 14H20V12H22V14ZM18 18H16V16H18V18ZM14 22H12V20H14V22Z" />
</svg> </svg>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,178 @@
import { ref, computed, type Ref, onUnmounted, toRef, isRef } from 'vue';
import type { Sprite } from '@/types/sprites';
export interface AnimationFramesOptions {
sprites: Ref<Sprite[]> | Sprite[] | (() => Sprite[]);
onDraw: () => void;
}
export function useAnimationFrames(options: AnimationFramesOptions) {
const { onDraw } = options;
// Convert sprites to a computed ref for reactivity
const spritesRef = computed(() => {
if (typeof options.sprites === 'function') {
return options.sprites();
}
if (isRef(options.sprites)) {
return options.sprites.value;
}
return options.sprites;
});
// Helper to get sprites array
const getSprites = () => spritesRef.value;
// State
const currentFrameIndex = ref(0);
const isPlaying = ref(false);
const fps = ref(12);
const hiddenFrames = ref<number[]>([]);
// Animation internals
const animationFrameId = ref<number | null>(null);
const lastFrameTime = ref(0);
// Computed properties for visible frames
const visibleFrames = computed(() => getSprites().filter((_, index) => !hiddenFrames.value.includes(index)));
const visibleFramesCount = computed(() => visibleFrames.value.length);
const visibleFrameIndex = computed(() => {
const sprites = getSprites();
const currentSprite = sprites[currentFrameIndex.value];
return visibleFrames.value.findIndex(s => s === currentSprite);
});
const visibleFrameNumber = computed(() => visibleFrameIndex.value + 1);
// Animation control
const animateFrame = () => {
const now = performance.now();
const elapsed = now - lastFrameTime.value;
const frameTime = 1000 / fps.value;
if (elapsed >= frameTime) {
lastFrameTime.value = now - (elapsed % frameTime);
nextFrame();
}
animationFrameId.value = requestAnimationFrame(animateFrame);
};
const startAnimation = () => {
lastFrameTime.value = performance.now();
animateFrame();
};
const stopAnimation = () => {
if (animationFrameId.value !== null) {
cancelAnimationFrame(animationFrameId.value);
animationFrameId.value = null;
}
};
const togglePlayback = () => {
isPlaying.value = !isPlaying.value;
if (isPlaying.value) {
startAnimation();
} else {
stopAnimation();
}
};
const nextFrame = () => {
if (visibleFrames.value.length === 0) return;
const sprites = getSprites();
const currentVisibleIndex = visibleFrameIndex.value;
const nextVisibleIndex = (currentVisibleIndex + 1) % visibleFrames.value.length;
currentFrameIndex.value = sprites.indexOf(visibleFrames.value[nextVisibleIndex]);
onDraw();
};
const previousFrame = () => {
if (visibleFrames.value.length === 0) return;
const sprites = getSprites();
const currentVisibleIndex = visibleFrameIndex.value;
const prevVisibleIndex = (currentVisibleIndex - 1 + visibleFrames.value.length) % visibleFrames.value.length;
currentFrameIndex.value = sprites.indexOf(visibleFrames.value[prevVisibleIndex]);
onDraw();
};
const handleSliderInput = (event: Event) => {
const sprites = getSprites();
const target = event.target as HTMLInputElement;
const index = parseInt(target.value);
currentFrameIndex.value = sprites.indexOf(visibleFrames.value[index]);
};
// Frame visibility management
const toggleHiddenFrame = (index: number) => {
const sprites = getSprites();
const currentIndex = hiddenFrames.value.indexOf(index);
if (currentIndex === -1) {
hiddenFrames.value.push(index);
// If hiding current frame, switch to next visible
if (index === currentFrameIndex.value) {
const nextVisible = sprites.findIndex((_, i) => i !== index && !hiddenFrames.value.includes(i));
if (nextVisible !== -1) {
currentFrameIndex.value = nextVisible;
}
}
} else {
hiddenFrames.value.splice(currentIndex, 1);
}
onDraw();
};
const showAllFrames = () => {
hiddenFrames.value = [];
onDraw();
};
const hideAllFrames = () => {
const sprites = getSprites();
hiddenFrames.value = sprites.map((_, index) => index);
// Keep at least one frame visible
if (hiddenFrames.value.length > 0) {
hiddenFrames.value.splice(currentFrameIndex.value, 1);
}
onDraw();
};
// Cleanup on unmount
onUnmounted(() => {
stopAnimation();
});
return {
// State
currentFrameIndex,
isPlaying,
fps,
hiddenFrames,
// Computed
visibleFrames,
visibleFramesCount,
visibleFrameIndex,
visibleFrameNumber,
// Methods
togglePlayback,
nextFrame,
previousFrame,
handleSliderInput,
toggleHiddenFrame,
showAllFrames,
hideAllFrames,
stopAnimation,
};
}

View File

@@ -0,0 +1,48 @@
import matter from 'gray-matter';
export interface BlogPost {
slug: string;
title: string;
date: string;
description: string;
image: string;
content: string;
keywords?: string;
author?: string;
}
export function useBlog() {
const getPosts = async (): Promise<BlogPost[]> => {
const modules = import.meta.glob('../blog/*.md', { query: '?raw', import: 'default' });
const posts: BlogPost[] = [];
for (const path in modules) {
const content = (await modules[path]()) as string;
const { data, content: markdownContent } = matter(content);
const slug = path.split('/').pop()?.replace('.md', '') || '';
posts.push({
slug,
title: data.title,
date: data.date,
description: data.description,
image: data.image,
content: markdownContent,
keywords: data.keywords,
author: data.author,
});
}
return posts.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
};
const getPost = async (slug: string): Promise<BlogPost | undefined> => {
const posts = await getPosts();
return posts.find(post => post.slug === slug);
};
return {
getPosts,
getPost,
};
}

View File

@@ -0,0 +1,151 @@
import { ref, type Ref } from 'vue';
import { useSettingsStore } from '@/stores/useSettingsStore';
import type { Sprite } from '@/types/sprites';
export interface Canvas2DOptions {
pixelPerfect?: Ref<boolean> | boolean;
}
export function useCanvas2D(canvasRef: Ref<HTMLCanvasElement | null>, options?: Canvas2DOptions) {
const ctx = ref<CanvasRenderingContext2D | null>(null);
const settingsStore = useSettingsStore();
const initContext = () => {
if (canvasRef.value) {
ctx.value = canvasRef.value.getContext('2d');
applySmoothing();
}
return ctx.value;
};
const applySmoothing = () => {
if (ctx.value) {
const pixelPerfect = options?.pixelPerfect;
const isPixelPerfect = typeof pixelPerfect === 'boolean' ? pixelPerfect : (pixelPerfect?.value ?? settingsStore.pixelPerfect);
ctx.value.imageSmoothingEnabled = !isPixelPerfect;
}
};
const clear = () => {
if (!canvasRef.value || !ctx.value) return;
ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);
};
const setCanvasSize = (width: number, height: number) => {
if (canvasRef.value) {
canvasRef.value.width = width;
canvasRef.value.height = height;
}
};
const fillRect = (x: number, y: number, width: number, height: number, color: string) => {
if (!ctx.value) return;
ctx.value.fillStyle = color;
ctx.value.fillRect(Math.floor(x), Math.floor(y), width, height);
};
const strokeRect = (x: number, y: number, width: number, height: number, color: string, lineWidth = 1) => {
if (!ctx.value) return;
ctx.value.strokeStyle = color;
ctx.value.lineWidth = lineWidth;
ctx.value.strokeRect(Math.floor(x), Math.floor(y), width, height);
};
const drawImage = (img: HTMLImageElement | HTMLCanvasElement, x: number, y: number, alpha = 1) => {
if (!ctx.value) return;
const prevAlpha = ctx.value.globalAlpha;
ctx.value.globalAlpha = alpha;
ctx.value.drawImage(img, Math.floor(x), Math.floor(y));
ctx.value.globalAlpha = prevAlpha;
};
const setGlobalAlpha = (alpha: number) => {
if (ctx.value) {
ctx.value.globalAlpha = alpha;
}
};
const resetGlobalAlpha = () => {
if (ctx.value) {
ctx.value.globalAlpha = 1.0;
}
};
// Helper to ensure integer positions for pixel-perfect rendering
const ensureIntegerPositions = <T extends { x: number; y: number }>(items: T[]) => {
items.forEach(item => {
item.x = Math.floor(item.x);
item.y = Math.floor(item.y);
});
};
// Centralized force redraw handler
const createForceRedrawHandler = <T extends { x: number; y: number }>(items: T[], drawCallback: () => void) => {
return () => {
ensureIntegerPositions(items);
applySmoothing();
drawCallback();
};
};
// Get mouse position relative to canvas, accounting for zoom
const getMousePosition = (event: MouseEvent, zoom = 1): { x: number; y: number } | null => {
if (!canvasRef.value) return null;
const rect = canvasRef.value.getBoundingClientRect();
const scaleX = canvasRef.value.width / (rect.width / zoom);
const scaleY = canvasRef.value.height / (rect.height / zoom);
return {
x: ((event.clientX - rect.left) / zoom) * scaleX,
y: ((event.clientY - rect.top) / zoom) * scaleY,
};
};
// Helper to attach load/error listeners to images that aren't yet loaded
const attachImageListeners = (sprites: Sprite[], onLoad: () => void, tracked: WeakSet<HTMLImageElement>) => {
sprites.forEach(sprite => {
const img = sprite.img as HTMLImageElement | undefined;
if (img && !tracked.has(img)) {
tracked.add(img);
if (!img.complete) {
img.addEventListener('load', onLoad, { once: true });
img.addEventListener('error', onLoad, { once: true });
}
}
});
};
// Fill cell background with selected color or transparent
const fillCellBackground = (x: number, y: number, width: number, height: number) => {
if (settingsStore.backgroundColor === 'transparent') return;
const color = settingsStore.backgroundColor === 'custom' ? settingsStore.backgroundColor : settingsStore.backgroundColor;
fillRect(x, y, width, height, color);
};
// Stroke grid with theme-aware color
const strokeGridCell = (x: number, y: number, width: number, height: number) => {
const color = settingsStore.darkMode ? '#4B5563' : '#e5e7eb';
strokeRect(x, y, width, height, color, 1);
};
return {
ctx,
canvasRef,
initContext,
applySmoothing,
clear,
setCanvasSize,
fillRect,
strokeRect,
drawImage,
setGlobalAlpha,
resetGlobalAlpha,
ensureIntegerPositions,
createForceRedrawHandler,
getMousePosition,
attachImageListeners,
fillCellBackground,
strokeGridCell,
};
}

View File

@@ -0,0 +1,323 @@
import { ref, computed, type Ref, type ComputedRef } from 'vue';
import type { Sprite, Layer } from '@/types/sprites';
import { getMaxDimensions } from './useSprites';
import { calculateNegativeSpacing } from './useNegativeSpacing';
export interface CellPosition {
col: number;
row: number;
index: number;
}
export interface SpritePosition {
id: string;
canvasX: number;
canvasY: number;
cellX: number;
cellY: number;
width: number;
height: number;
maxWidth: number;
maxHeight: number;
col: number;
row: number;
index: number;
x: number;
y: number;
}
export interface DragSpriteOptions {
sprites: Ref<Sprite[]> | ComputedRef<Sprite[]> | Sprite[];
layers?: Ref<Layer[]> | ComputedRef<Layer[]> | Layer[];
columns: Ref<number> | number;
zoom?: Ref<number>;
allowCellSwap?: Ref<boolean>;
negativeSpacingEnabled?: Ref<boolean>;
manualCellSizeEnabled?: Ref<boolean>;
manualCellWidth?: Ref<number>;
manualCellHeight?: Ref<number>;
getMousePosition: (event: MouseEvent, zoom?: number) => { x: number; y: number } | null;
onUpdateSprite: (id: string, x: number, y: number) => void;
onUpdateSpriteCell?: (id: string, newIndex: number) => void;
onDraw: () => void;
}
export function useDragSprite(options: DragSpriteOptions) {
const { getMousePosition, onUpdateSprite, onUpdateSpriteCell, onDraw } = options;
// Helper to get reactive values
const getSprites = () => (Array.isArray(options.sprites) ? options.sprites : options.sprites.value);
const getLayers = () => (options.layers ? (Array.isArray(options.layers) ? options.layers : options.layers.value) : null);
const getColumns = () => (typeof options.columns === 'number' ? options.columns : options.columns.value);
const getZoom = () => options.zoom?.value ?? 1;
const getAllowCellSwap = () => options.allowCellSwap?.value ?? false;
const getNegativeSpacingEnabled = () => options.negativeSpacingEnabled?.value ?? false;
const getManualCellSizeEnabled = () => options.manualCellSizeEnabled?.value ?? false;
const getManualCellWidth = () => options.manualCellWidth?.value ?? 64;
const getManualCellHeight = () => options.manualCellHeight?.value ?? 64;
// Drag state
const isDragging = ref(false);
const activeSpriteId = ref<string | null>(null);
const activeSpriteCellIndex = ref<number | null>(null);
const dragStartX = ref(0);
const dragStartY = ref(0);
const dragOffsetX = ref(0);
const dragOffsetY = ref(0);
const currentHoverCell = ref<CellPosition | null>(null);
// Visual feedback
const ghostSprite = ref<{ id: string; x: number; y: number } | null>(null);
const highlightCell = ref<CellPosition | null>(null);
// Cache for max dimensions
const lastMaxWidth = ref(1);
const lastMaxHeight = ref(1);
const calculateMaxDimensions = () => {
const negativeSpacingEnabled = getNegativeSpacingEnabled();
const manualCellSizeEnabled = getManualCellSizeEnabled();
// If manual cell size is enabled, use manual dimensions
if (manualCellSizeEnabled) {
const maxWidth = getManualCellWidth();
const maxHeight = getManualCellHeight();
// When manual cell size is used, negative spacing is not applied
const negativeSpacing = 0;
// Don't update lastMaxWidth/lastMaxHeight when in manual mode
return { maxWidth, maxHeight, negativeSpacing };
}
// Get all sprites to calculate dimensions from
// If layers are provided, use all visible layers; otherwise use current sprites
const layers = getLayers();
const spritesToMeasure = layers ? layers.filter(l => l.visible).flatMap(l => l.sprites) : getSprites();
// Otherwise, calculate based on sprite dimensions across all visible layers
const base = getMaxDimensions(spritesToMeasure);
// When switching back from manual mode, reset to actual sprite dimensions
const baseMaxWidth = Math.max(1, base.maxWidth);
const baseMaxHeight = Math.max(1, base.maxHeight);
lastMaxWidth.value = baseMaxWidth;
lastMaxHeight.value = baseMaxHeight;
// Calculate negative spacing using shared composable
const negativeSpacing = calculateNegativeSpacing(spritesToMeasure, negativeSpacingEnabled);
// Add negative spacing to expand each cell
const maxWidth = baseMaxWidth + negativeSpacing;
const maxHeight = baseMaxHeight + negativeSpacing;
return { maxWidth, maxHeight, negativeSpacing };
};
// Computed sprite positions
const spritePositions = computed<SpritePosition[]>(() => {
const sprites = getSprites();
const columns = getColumns();
const { maxWidth, maxHeight, negativeSpacing } = calculateMaxDimensions();
return sprites.map((sprite, index) => {
const col = index % columns;
const row = Math.floor(index / columns);
// With negative spacing, sprites are positioned at bottom-right of cell
// (spacing added to top and left)
return {
id: sprite.id,
canvasX: col * maxWidth + negativeSpacing + sprite.x,
canvasY: row * maxHeight + negativeSpacing + sprite.y,
cellX: col * maxWidth,
cellY: row * maxHeight,
width: sprite.width,
height: sprite.height,
maxWidth,
maxHeight,
col,
row,
index,
x: sprite.x,
y: sprite.y,
};
});
});
const findCellAtPosition = (x: number, y: number): CellPosition | null => {
const sprites = getSprites();
const columns = getColumns();
const { maxWidth, maxHeight } = calculateMaxDimensions();
const col = Math.floor(x / maxWidth);
const row = Math.floor(y / maxHeight);
const totalRows = Math.ceil(sprites.length / columns);
if (col >= 0 && col < columns && row >= 0 && row < totalRows) {
const index = row * columns + col;
if (index < sprites.length) {
return { col, row, index };
}
}
return null;
};
const findSpriteAtPosition = (x: number, y: number): Sprite | null => {
const sprites = getSprites();
const positions = spritePositions.value;
for (let i = positions.length - 1; i >= 0; i--) {
const pos = positions[i];
if (x >= pos.canvasX && x <= pos.canvasX + pos.width && y >= pos.canvasY && y <= pos.canvasY + pos.height) {
return sprites.find(s => s.id === pos.id) || null;
}
}
return null;
};
const startDrag = (event: MouseEvent) => {
const pos = getMousePosition(event, getZoom());
if (!pos) return;
const clickedSprite = findSpriteAtPosition(pos.x, pos.y);
if (clickedSprite) {
isDragging.value = true;
activeSpriteId.value = clickedSprite.id;
dragStartX.value = pos.x;
dragStartY.value = pos.y;
const spritePosition = spritePositions.value.find(p => p.id === clickedSprite.id);
if (spritePosition) {
dragOffsetX.value = pos.x - spritePosition.canvasX;
dragOffsetY.value = pos.y - spritePosition.canvasY;
activeSpriteCellIndex.value = spritePosition.index;
const startCell = findCellAtPosition(pos.x, pos.y);
if (startCell) {
currentHoverCell.value = startCell;
highlightCell.value = null;
}
}
}
};
const handleInCellMovement = (mouseX: number, mouseY: number, spriteIndex: number) => {
if (!activeSpriteId.value) return;
const sprites = getSprites();
const columns = getColumns();
const { maxWidth, maxHeight, negativeSpacing } = calculateMaxDimensions();
// Use the sprite's current index in the array to calculate cell position
const cellCol = spriteIndex % columns;
const cellRow = Math.floor(spriteIndex / columns);
const cellX = cellCol * maxWidth;
const cellY = cellRow * maxHeight;
// Calculate new position relative to cell origin (without the negative spacing offset)
// The sprite's x,y is stored relative to where it would be drawn after the negativeSpacing offset
const newX = mouseX - cellX - negativeSpacing - dragOffsetX.value;
const newY = mouseY - cellY - negativeSpacing - dragOffsetY.value;
// The sprite can move within the full expanded cell area
// Allow negative values up to -negativeSpacing so sprite can fill the expanded area
const constrainedX = Math.floor(Math.max(-negativeSpacing, Math.min(maxWidth - negativeSpacing - sprites[spriteIndex].width, newX)));
const constrainedY = Math.floor(Math.max(-negativeSpacing, Math.min(maxHeight - negativeSpacing - sprites[spriteIndex].height, newY)));
onUpdateSprite(activeSpriteId.value, constrainedX, constrainedY);
onDraw();
};
const drag = (event: MouseEvent) => {
if (!isDragging.value || !activeSpriteId.value || activeSpriteCellIndex.value === null) return;
const pos = getMousePosition(event, getZoom());
if (!pos) return;
const sprites = getSprites();
const spriteIndex = sprites.findIndex(s => s.id === activeSpriteId.value);
if (spriteIndex === -1) return;
const hoverCell = findCellAtPosition(pos.x, pos.y);
currentHoverCell.value = hoverCell;
if (getAllowCellSwap() && hoverCell) {
if (hoverCell.index !== activeSpriteCellIndex.value) {
highlightCell.value = hoverCell;
ghostSprite.value = {
id: activeSpriteId.value,
x: pos.x - dragOffsetX.value,
y: pos.y - dragOffsetY.value,
};
onDraw();
} else {
highlightCell.value = null;
ghostSprite.value = null;
handleInCellMovement(pos.x, pos.y, spriteIndex);
}
} else {
handleInCellMovement(pos.x, pos.y, spriteIndex);
}
};
const stopDrag = () => {
if (isDragging.value && getAllowCellSwap() && activeSpriteId.value && activeSpriteCellIndex.value !== null && currentHoverCell.value && activeSpriteCellIndex.value !== currentHoverCell.value.index) {
if (onUpdateSpriteCell) {
onUpdateSpriteCell(activeSpriteId.value, currentHoverCell.value.index);
}
onUpdateSprite(activeSpriteId.value, 0, 0);
}
isDragging.value = false;
activeSpriteId.value = null;
activeSpriteCellIndex.value = null;
currentHoverCell.value = null;
highlightCell.value = null;
ghostSprite.value = null;
onDraw();
};
// Touch event handlers
const handleTouchStart = (event: TouchEvent) => {
if (event.touches.length === 1) {
const touch = event.touches[0];
const mouseEvent = {
clientX: touch.clientX,
clientY: touch.clientY,
preventDefault: () => {},
} as unknown as MouseEvent;
startDrag(mouseEvent);
}
};
const handleTouchMove = (event: TouchEvent) => {
if (isDragging.value) {
event.preventDefault();
}
if (event.touches.length === 1) {
const touch = event.touches[0];
const mouseEvent = {
clientX: touch.clientX,
clientY: touch.clientY,
preventDefault: () => {},
} as unknown as MouseEvent;
drag(mouseEvent);
}
};
return {
// State
isDragging,
activeSpriteId,
ghostSprite,
highlightCell,
spritePositions,
// Methods
startDrag,
drag,
stopDrag,
handleTouchStart,
handleTouchMove,
findSpriteAtPosition,
findCellAtPosition,
calculateMaxDimensions,
};
}

View File

@@ -0,0 +1,251 @@
import type { Ref } from 'vue';
import GIF from 'gif.js';
import gifWorkerUrl from 'gif.js/dist/gif.worker.js?url';
import JSZip from 'jszip';
import type { Sprite } from '../types/sprites';
import { getMaxDimensions } from './useSprites';
import { calculateNegativeSpacing } from './useNegativeSpacing';
export const useExport = (sprites: Ref<Sprite[]>, columns: Ref<number>, negativeSpacingEnabled: Ref<boolean>, backgroundColor?: Ref<string>, manualCellSizeEnabled?: Ref<boolean>, manualCellWidth?: Ref<number>, manualCellHeight?: Ref<number>) => {
const getCellDimensions = () => {
// If manual cell size is enabled, use manual values
if (manualCellSizeEnabled?.value) {
return {
cellWidth: manualCellWidth?.value ?? 64,
cellHeight: manualCellHeight?.value ?? 64,
negativeSpacing: 0,
};
}
// Otherwise, calculate from sprite dimensions
const { maxWidth, maxHeight } = getMaxDimensions(sprites.value);
const negativeSpacing = calculateNegativeSpacing(sprites.value, negativeSpacingEnabled.value);
return {
cellWidth: maxWidth + negativeSpacing,
cellHeight: maxHeight + negativeSpacing,
negativeSpacing,
};
};
const downloadSpritesheet = () => {
if (!sprites.value.length) {
alert('Please upload or import sprites before downloading the spritesheet.');
return;
}
const { cellWidth, cellHeight, negativeSpacing } = getCellDimensions();
const rows = Math.ceil(sprites.value.length / columns.value);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = cellWidth * columns.value;
canvas.height = cellHeight * rows;
ctx.imageSmoothingEnabled = false;
// Apply background color if not transparent
if (backgroundColor?.value && backgroundColor.value !== 'transparent') {
ctx.fillStyle = backgroundColor.value;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
sprites.value.forEach((sprite, index) => {
const col = index % columns.value;
const row = Math.floor(index / columns.value);
const cellX = Math.floor(col * cellWidth);
const cellY = Math.floor(row * cellHeight);
ctx.drawImage(sprite.img, Math.floor(cellX + negativeSpacing + sprite.x), Math.floor(cellY + negativeSpacing + sprite.y));
});
const link = document.createElement('a');
link.download = 'spritesheet.png';
link.href = canvas.toDataURL('image/png', 1.0);
link.click();
};
const exportSpritesheetJSON = async () => {
if (!sprites.value.length) {
alert('Nothing to export. Please add sprites first.');
return;
}
const spritesData = await Promise.all(
sprites.value.map(async sprite => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return null;
canvas.width = sprite.width;
canvas.height = sprite.height;
ctx.drawImage(sprite.img, 0, 0);
const base64Data = canvas.toDataURL('image/png');
return {
id: sprite.id,
width: sprite.width,
height: sprite.height,
x: sprite.x,
y: sprite.y,
base64: base64Data,
name: sprite.file.name,
};
})
);
const jsonData = {
columns: columns.value,
negativeSpacingEnabled: negativeSpacingEnabled.value,
backgroundColor: backgroundColor?.value || 'transparent',
manualCellSizeEnabled: manualCellSizeEnabled?.value || false,
manualCellWidth: manualCellWidth?.value || 64,
manualCellHeight: manualCellHeight?.value || 64,
sprites: spritesData.filter(Boolean),
};
const jsonString = JSON.stringify(jsonData, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'spritesheet.json';
link.href = url;
link.click();
URL.revokeObjectURL(url);
};
const importSpritesheetJSON = async (jsonFile: File) => {
const jsonText = await jsonFile.text();
const jsonData = JSON.parse(jsonText);
if (!jsonData.sprites || !Array.isArray(jsonData.sprites)) throw new Error('Invalid JSON format: missing sprites array');
if (jsonData.columns && typeof jsonData.columns === 'number') columns.value = jsonData.columns;
if (typeof jsonData.negativeSpacingEnabled === 'boolean') negativeSpacingEnabled.value = jsonData.negativeSpacingEnabled;
if (typeof jsonData.backgroundColor === 'string' && backgroundColor) backgroundColor.value = jsonData.backgroundColor;
if (typeof jsonData.manualCellSizeEnabled === 'boolean' && manualCellSizeEnabled) manualCellSizeEnabled.value = jsonData.manualCellSizeEnabled;
if (typeof jsonData.manualCellWidth === 'number' && manualCellWidth) manualCellWidth.value = jsonData.manualCellWidth;
if (typeof jsonData.manualCellHeight === 'number' && manualCellHeight) manualCellHeight.value = jsonData.manualCellHeight;
// revoke existing blob urls
if (sprites.value.length) {
sprites.value.forEach(s => {
if (s.url && s.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(s.url);
} catch {}
}
});
}
const imported = await Promise.all(
jsonData.sprites.map((spriteData: any) => {
return new Promise<Sprite>(resolve => {
const img = new Image();
img.onload = () => {
const byteString = atob(spriteData.base64.split(',')[1]);
const mimeType = spriteData.base64.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);
const blob = new Blob([ab], { type: mimeType });
const fileName = spriteData.name || `sprite-${spriteData.id}.png`;
const file = new File([blob], fileName, { type: mimeType });
resolve({
id: spriteData.id || crypto.randomUUID(),
file,
img,
url: spriteData.base64,
width: spriteData.width,
height: spriteData.height,
x: spriteData.x || 0,
y: spriteData.y || 0,
});
};
img.src = spriteData.base64;
});
})
);
sprites.value = imported;
};
const downloadAsGif = (fps: number) => {
if (!sprites.value.length) {
alert('Please upload or import sprites before generating a GIF.');
return;
}
const { cellWidth, cellHeight, negativeSpacing } = getCellDimensions();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = cellWidth;
canvas.height = cellHeight;
ctx.imageSmoothingEnabled = false;
const gif = new GIF({ workers: 2, quality: 10, width: cellWidth, height: cellHeight, workerScript: gifWorkerUrl });
sprites.value.forEach(sprite => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Apply background color if not transparent
if (backgroundColor?.value && backgroundColor.value !== 'transparent') {
ctx.fillStyle = backgroundColor.value;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(sprite.img, Math.floor(negativeSpacing + sprite.x), Math.floor(negativeSpacing + sprite.y));
gif.addFrame(ctx, { copy: true, delay: 1000 / fps });
});
gif.on('finished', (blob: Blob) => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = 'animation.gif';
link.href = url;
link.click();
URL.revokeObjectURL(url);
});
gif.render();
};
const downloadAsZip = async () => {
if (!sprites.value.length) {
alert('Please upload or import sprites before downloading a ZIP.');
return;
}
const zip = new JSZip();
const { cellWidth, cellHeight, negativeSpacing } = getCellDimensions();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = cellWidth;
canvas.height = cellHeight;
ctx.imageSmoothingEnabled = false;
sprites.value.forEach((sprite, index) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Apply background color if not transparent
if (backgroundColor?.value && backgroundColor.value !== 'transparent') {
ctx.fillStyle = backgroundColor.value;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(sprite.img, Math.floor(negativeSpacing + sprite.x), Math.floor(negativeSpacing + sprite.y));
const dataURL = canvas.toDataURL('image/png');
const binary = atob(dataURL.split(',')[1]);
const buf = new ArrayBuffer(binary.length);
const view = new Uint8Array(buf);
for (let i = 0; i < binary.length; i++) view[i] = binary.charCodeAt(i);
const baseName = sprite.file?.name ? sprite.file.name.replace(/\s+/g, '_') : `sprite_${index + 1}.png`;
const name = `${index + 1}_${baseName}`;
zip.file(name, view);
});
const content = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(content);
const link = document.createElement('a');
link.download = 'sprites.zip';
link.href = url;
link.click();
URL.revokeObjectURL(url);
};
return { downloadSpritesheet, exportSpritesheetJSON, importSpritesheetJSON, downloadAsGif, downloadAsZip };
};

View File

@@ -0,0 +1,304 @@
import type { Ref } from 'vue';
import GIF from 'gif.js';
import gifWorkerUrl from 'gif.js/dist/gif.worker.js?url';
import JSZip from 'jszip';
import type { Layer, Sprite } from '@/types/sprites';
import { getMaxDimensionsAcrossLayers } from './useLayers';
import { calculateNegativeSpacing } from './useNegativeSpacing';
export const useExportLayers = (layersRef: Ref<Layer[]>, columns: Ref<number>, negativeSpacingEnabled: Ref<boolean>, activeLayerId?: Ref<string>, backgroundColor?: Ref<string>, manualCellSizeEnabled?: Ref<boolean>, manualCellWidth?: Ref<number>, manualCellHeight?: Ref<number>) => {
const getVisibleLayers = () => layersRef.value.filter(l => l.visible);
const getAllVisibleSprites = () => getVisibleLayers().flatMap(l => l.sprites);
const getCellDimensions = () => {
// If manual cell size is enabled, use manual values
if (manualCellSizeEnabled?.value) {
return {
cellWidth: manualCellWidth?.value ?? 64,
cellHeight: manualCellHeight?.value ?? 64,
negativeSpacing: 0,
};
}
// Otherwise, calculate from sprite dimensions
const visibleLayers = getVisibleLayers();
const { maxWidth, maxHeight } = getMaxDimensionsAcrossLayers(visibleLayers);
const negativeSpacing = calculateNegativeSpacing(getAllVisibleSprites(), negativeSpacingEnabled.value);
return {
cellWidth: maxWidth + negativeSpacing,
cellHeight: maxHeight + negativeSpacing,
negativeSpacing,
};
};
const drawCompositeCell = (ctx: CanvasRenderingContext2D, cellIndex: number, cellWidth: number, cellHeight: number, negativeSpacing: number) => {
ctx.clearRect(0, 0, cellWidth, cellHeight);
// Apply background color if not transparent
if (backgroundColor?.value && backgroundColor.value !== 'transparent') {
ctx.fillStyle = backgroundColor.value;
ctx.fillRect(0, 0, cellWidth, cellHeight);
}
const vLayers = getVisibleLayers();
vLayers.forEach(layer => {
const sprite = layer.sprites[cellIndex];
if (!sprite) return;
ctx.drawImage(sprite.img, Math.floor(negativeSpacing + sprite.x), Math.floor(negativeSpacing + sprite.y));
});
};
const downloadSpritesheet = () => {
const visibleLayers = getVisibleLayers();
if (!visibleLayers.length || !visibleLayers.some(l => l.sprites.length)) {
alert('Please upload or import sprites before downloading the spritesheet.');
return;
}
const { cellWidth, cellHeight, negativeSpacing } = getCellDimensions();
const maxLen = Math.max(...visibleLayers.map(l => l.sprites.length));
const rows = Math.ceil(maxLen / columns.value);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = cellWidth * columns.value;
canvas.height = cellHeight * rows;
ctx.imageSmoothingEnabled = false;
// Apply background color to entire canvas if not transparent
if (backgroundColor?.value && backgroundColor.value !== 'transparent') {
ctx.fillStyle = backgroundColor.value;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
for (let index = 0; index < maxLen; index++) {
const col = index % columns.value;
const row = Math.floor(index / columns.value);
const cellX = Math.floor(col * cellWidth);
const cellY = Math.floor(row * cellHeight);
const cellCanvas = document.createElement('canvas');
const cellCtx = cellCanvas.getContext('2d');
if (!cellCtx) return;
cellCanvas.width = cellWidth;
cellCanvas.height = cellHeight;
cellCtx.imageSmoothingEnabled = false;
drawCompositeCell(cellCtx, index, cellWidth, cellHeight, negativeSpacing);
ctx.drawImage(cellCanvas, cellX, cellY);
}
const link = document.createElement('a');
link.download = 'spritesheet.png';
link.href = canvas.toDataURL('image/png', 1.0);
link.click();
};
const exportSpritesheetJSON = async () => {
const visibleLayers = getVisibleLayers();
if (!visibleLayers.length || !visibleLayers.some(l => l.sprites.length)) {
alert('Nothing to export. Please add sprites first.');
return;
}
const layersData = await Promise.all(
layersRef.value.map(async layer => {
const sprites = await Promise.all(
layer.sprites.map(async sprite => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return null;
canvas.width = sprite.width;
canvas.height = sprite.height;
ctx.drawImage(sprite.img, 0, 0);
const base64 = canvas.toDataURL('image/png');
return { id: sprite.id, width: sprite.width, height: sprite.height, x: sprite.x, y: sprite.y, base64, name: sprite.file.name };
})
);
return { id: layer.id, name: layer.name, visible: layer.visible, locked: layer.locked, sprites: sprites.filter(Boolean) };
})
);
const json = {
version: 2,
columns: columns.value,
negativeSpacingEnabled: negativeSpacingEnabled.value,
backgroundColor: backgroundColor?.value || 'transparent',
manualCellSizeEnabled: manualCellSizeEnabled?.value || false,
manualCellWidth: manualCellWidth?.value || 64,
manualCellHeight: manualCellHeight?.value || 64,
layers: layersData,
};
const jsonString = JSON.stringify(json, null, 2);
const blob = new Blob([jsonString], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'spritesheet.json';
a.click();
URL.revokeObjectURL(url);
};
const importSpritesheetJSON = async (jsonFile: File) => {
const text = await jsonFile.text();
const data = JSON.parse(text);
const loadSprite = (spriteData: any) =>
new Promise<Sprite>(resolve => {
const img = new Image();
img.onload = () => {
const byteString = atob(spriteData.base64.split(',')[1]);
const mimeType = spriteData.base64.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) ia[i] = byteString.charCodeAt(i);
const blob = new Blob([ab], { type: mimeType });
const fileName = spriteData.name || `sprite-${spriteData.id}.png`;
const file = new File([blob], fileName, { type: mimeType });
resolve({ id: spriteData.id || crypto.randomUUID(), file, img, url: spriteData.base64, width: spriteData.width, height: spriteData.height, x: spriteData.x || 0, y: spriteData.y || 0 });
};
img.src = spriteData.base64;
});
if (typeof data.columns === 'number') columns.value = data.columns;
if (typeof data.negativeSpacingEnabled === 'boolean') negativeSpacingEnabled.value = data.negativeSpacingEnabled;
if (typeof data.backgroundColor === 'string' && backgroundColor) backgroundColor.value = data.backgroundColor;
if (typeof data.manualCellSizeEnabled === 'boolean' && manualCellSizeEnabled) manualCellSizeEnabled.value = data.manualCellSizeEnabled;
if (typeof data.manualCellWidth === 'number' && manualCellWidth) manualCellWidth.value = data.manualCellWidth;
if (typeof data.manualCellHeight === 'number' && manualCellHeight) manualCellHeight.value = data.manualCellHeight;
if (Array.isArray(data.layers)) {
const newLayers: Layer[] = [];
for (const layerData of data.layers) {
const sprites: Sprite[] = await Promise.all(layerData.sprites.map((s: any) => loadSprite(s)));
newLayers.push({ id: layerData.id || crypto.randomUUID(), name: layerData.name || 'Layer', visible: layerData.visible !== false, locked: !!layerData.locked, sprites });
}
// Ensure at least one layer with sprites is visible
if (newLayers.length > 0 && !newLayers.some(l => l.visible && l.sprites.length > 0)) {
const firstLayerWithSprites = newLayers.find(l => l.sprites.length > 0);
if (firstLayerWithSprites) {
firstLayerWithSprites.visible = true;
}
}
layersRef.value = newLayers;
// Set active layer to the first layer with sprites
if (activeLayerId && newLayers.length > 0) {
const firstWithSprites = newLayers.find(l => l.sprites.length > 0);
activeLayerId.value = firstWithSprites ? firstWithSprites.id : newLayers[0].id;
}
return;
}
if (Array.isArray(data.sprites)) {
const sprites: Sprite[] = await Promise.all(data.sprites.map((s: any) => loadSprite(s)));
const baseLayerId = crypto.randomUUID();
layersRef.value = [
{ id: baseLayerId, name: 'Base', visible: true, locked: false, sprites },
{ id: crypto.randomUUID(), name: 'Other', visible: true, locked: false, sprites: [] },
];
if (activeLayerId) {
activeLayerId.value = baseLayerId;
}
return;
}
throw new Error('Invalid JSON format');
};
const downloadAsGif = (fps: number) => {
const visibleLayers = getVisibleLayers();
if (!visibleLayers.length || !visibleLayers.some(l => l.sprites.length)) {
alert('Please upload or import sprites before generating a GIF.');
return;
}
const { cellWidth, cellHeight, negativeSpacing } = getCellDimensions();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = cellWidth;
canvas.height = cellHeight;
ctx.imageSmoothingEnabled = false;
const gif = new GIF({ workers: 2, quality: 10, width: cellWidth, height: cellHeight, workerScript: gifWorkerUrl });
const maxLen = Math.max(...visibleLayers.map(l => l.sprites.length));
for (let i = 0; i < maxLen; i++) {
drawCompositeCell(ctx, i, cellWidth, cellHeight, negativeSpacing);
gif.addFrame(ctx, { copy: true, delay: 1000 / fps });
}
gif.on('finished', (blob: Blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'animation.gif';
a.click();
URL.revokeObjectURL(url);
});
gif.render();
};
const downloadAsZip = async () => {
const visibleLayers = getVisibleLayers();
if (!visibleLayers.length || !visibleLayers.some(l => l.sprites.length)) {
alert('Please upload or import sprites before downloading a ZIP.');
return;
}
const zip = new JSZip();
const { cellWidth, cellHeight, negativeSpacing } = getCellDimensions();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) return;
canvas.width = cellWidth;
canvas.height = cellHeight;
ctx.imageSmoothingEnabled = false;
const maxLen = Math.max(...visibleLayers.map(l => l.sprites.length));
for (let i = 0; i < maxLen; i++) {
drawCompositeCell(ctx, i, cellWidth, cellHeight, negativeSpacing);
const dataURL = canvas.toDataURL('image/png');
const binary = atob(dataURL.split(',')[1]);
const buf = new ArrayBuffer(binary.length);
const view = new Uint8Array(buf);
for (let j = 0; j < binary.length; j++) view[j] = binary.charCodeAt(j);
zip.file(`frames/frame_${String(i + 1).padStart(3, '0')}.png`, view);
}
const jsonFolder = zip.folder('export')!;
const jsonBlobPromise = (async () => {
const layersPayload = await Promise.all(
layersRef.value.map(async layer => ({
id: layer.id,
name: layer.name,
visible: layer.visible,
locked: layer.locked,
sprites: await Promise.all(layer.sprites.map(async s => ({ id: s.id, width: s.width, height: s.height, x: s.x, y: s.y, name: s.file.name }))),
}))
);
const meta = {
version: 2,
columns: columns.value,
negativeSpacingEnabled: negativeSpacingEnabled.value,
backgroundColor: backgroundColor?.value || 'transparent',
manualCellSizeEnabled: manualCellSizeEnabled?.value || false,
manualCellWidth: manualCellWidth?.value || 64,
manualCellHeight: manualCellHeight?.value || 64,
layers: layersPayload,
};
const metaStr = JSON.stringify(meta, null, 2);
jsonFolder.file('spritesheet.meta.json', metaStr);
})();
await jsonBlobPromise;
const content = await zip.generateAsync({ type: 'blob' });
const url = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = url;
a.download = 'sprites.zip';
a.click();
URL.revokeObjectURL(url);
};
return { downloadSpritesheet, exportSpritesheetJSON, importSpritesheetJSON, downloadAsGif, downloadAsZip };
};

View File

@@ -0,0 +1,110 @@
import { ref, type Ref, type ComputedRef } from 'vue';
import type { Sprite } from '@/types/sprites';
import { getMaxDimensions } from './useSprites';
export interface FileDropOptions {
sprites: Ref<Sprite[]> | ComputedRef<Sprite[]> | Sprite[];
onAddSprite: (file: File) => void;
onAddSpriteWithResize: (file: File) => void;
}
export function useFileDrop(options: FileDropOptions) {
const { onAddSprite, onAddSpriteWithResize } = options;
// Helper to get sprites array
const getSprites = () => (Array.isArray(options.sprites) ? options.sprites : options.sprites.value);
const isDragOver = ref(false);
const handleDragOver = (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'copy';
}
isDragOver.value = true;
};
const handleDragEnter = (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
isDragOver.value = true;
};
const handleDragLeave = (event: DragEvent, canvasRef?: HTMLElement | null) => {
event.preventDefault();
event.stopPropagation();
if (canvasRef) {
const rect = canvasRef.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) {
isDragOver.value = false;
}
} else {
isDragOver.value = false;
}
};
const processDroppedImage = (file: File): Promise<void> => {
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();
reader.onload = e => {
if (e.target?.result) {
img.src = e.target.result as string;
}
};
img.onload = () => {
const sprites = getSprites();
const { maxWidth, maxHeight } = getMaxDimensions(sprites);
// Check if the dropped image is larger than current cells
if (img.naturalWidth > maxWidth || img.naturalHeight > maxHeight) {
onAddSpriteWithResize(file);
} else {
onAddSprite(file);
}
resolve();
};
img.onerror = () => {
console.error('Failed to load image:', file.name);
reject(new Error('Failed to load image'));
};
reader.readAsDataURL(file);
});
};
const handleDrop = async (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
isDragOver.value = false;
if (!event.dataTransfer?.files || event.dataTransfer.files.length === 0) {
return;
}
const files = Array.from(event.dataTransfer.files).filter(file => file.type.startsWith('image/'));
if (files.length === 0) {
alert('Please drop image files only.');
return;
}
// Process each dropped file
for (const file of files) {
await processDroppedImage(file);
}
};
return {
isDragOver,
handleDragOver,
handleDragEnter,
handleDragLeave,
handleDrop,
};
}

View File

@@ -0,0 +1,250 @@
import { computed, ref, watch } from 'vue';
import type { Layer, Sprite } from '@/types/sprites';
import { getMaxDimensions as getMaxDimensionsSingle, useSprites as useSpritesSingle } from './useSprites';
import { useSettingsStore } from '@/stores/useSettingsStore';
export const createEmptyLayer = (name: string): Layer => ({
id: crypto.randomUUID(),
name,
sprites: [],
visible: true,
locked: false,
});
const layers = ref<Layer[]>([createEmptyLayer('Base')]);
const activeLayerId = ref<string>(layers.value[0].id);
const columns = ref(4);
export const useLayers = () => {
const settingsStore = useSettingsStore();
watch(columns, val => {
const num = typeof val === 'number' ? val : parseInt(String(val));
const safe = Number.isFinite(num) && num >= 1 ? Math.min(num, 10) : 1;
if (safe !== columns.value) columns.value = safe;
});
const activeLayer = computed(() => layers.value.find(l => l.id === activeLayerId.value) || layers.value[0]);
const getMaxDimensions = (sprites: Sprite[]) => getMaxDimensionsSingle(sprites);
const visibleLayers = computed(() => layers.value.filter(l => l.visible));
const hasSprites = computed(() => layers.value.some(l => l.sprites.length > 0));
const updateSpritePosition = (id: string, x: number, y: number) => {
const l = activeLayer.value;
if (!l) return;
const i = l.sprites.findIndex(s => s.id === id);
if (i !== -1) {
l.sprites[i].x = Math.floor(x);
l.sprites[i].y = Math.floor(y);
}
};
const updateSpriteInLayer = (layerId: string, spriteId: string, x: number, y: number) => {
const l = layers.value.find(layer => layer.id === layerId);
if (!l) return;
const i = l.sprites.findIndex(s => s.id === spriteId);
if (i !== -1) {
l.sprites[i].x = Math.floor(x);
l.sprites[i].y = Math.floor(y);
}
};
const alignSprites = (position: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom') => {
const l = activeLayer.value;
if (!l || !l.sprites.length) return;
// Determine the cell dimensions to align within
let cellWidth: number;
let cellHeight: number;
if (settingsStore.manualCellSizeEnabled) {
// Use manual cell size (without negative spacing)
cellWidth = settingsStore.manualCellWidth;
cellHeight = settingsStore.manualCellHeight;
} else {
// Use auto-calculated dimensions based on ALL visible layers (not just active layer)
const { maxWidth, maxHeight } = getMaxDimensionsAcrossLayers(visibleLayers.value);
cellWidth = maxWidth;
cellHeight = maxHeight;
}
l.sprites = l.sprites.map(sprite => {
let x = sprite.x;
let y = sprite.y;
switch (position) {
case 'left':
x = 0;
break;
case 'center':
x = Math.floor((cellWidth - sprite.width) / 2);
break;
case 'right':
x = Math.floor(cellWidth - sprite.width);
break;
case 'top':
y = 0;
break;
case 'middle':
y = Math.floor((cellHeight - sprite.height) / 2);
break;
case 'bottom':
y = Math.floor(cellHeight - sprite.height);
break;
}
return { ...sprite, x: Math.floor(x), y: Math.floor(y) };
});
};
const updateSpriteCell = (id: string, newIndex: number) => {
const l = activeLayer.value;
if (!l) return;
const currentIndex = l.sprites.findIndex(s => s.id === id);
if (currentIndex === -1 || currentIndex === newIndex) return;
const next = [...l.sprites];
if (newIndex < next.length) {
const moving = { ...next[currentIndex] };
const target = { ...next[newIndex] };
next[currentIndex] = target;
next[newIndex] = moving;
} else {
const [moved] = next.splice(currentIndex, 1);
next.splice(newIndex, 0, moved);
}
l.sprites = next;
};
const removeSprite = (id: string) => {
const l = activeLayer.value;
if (!l) return;
const i = l.sprites.findIndex(s => s.id === id);
if (i === -1) return;
const s = l.sprites[i];
if (s.url && s.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(s.url);
} catch {}
}
l.sprites.splice(i, 1);
};
const replaceSprite = (id: string, file: File) => {
const l = activeLayer.value;
if (!l) return;
const i = l.sprites.findIndex(s => s.id === id);
if (i === -1) return;
const old = l.sprites[i];
if (old.url && old.url.startsWith('blob:')) {
try {
URL.revokeObjectURL(old.url);
} catch {}
}
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
l.sprites[i] = { id: old.id, file, img, url, width: img.width, height: img.height, x: old.x, y: old.y };
};
img.onerror = () => {
console.error('Failed to load replacement image:', file.name);
};
img.src = url;
};
reader.onerror = () => {
console.error('Failed to read replacement image file:', file.name);
};
reader.readAsDataURL(file);
};
const addSprite = (file: File) => {
const l = activeLayer.value;
if (!l) return;
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
const next: Sprite = {
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
};
l.sprites = [...l.sprites, next];
};
img.onerror = () => {
console.error('Failed to load sprite image:', file.name);
};
img.src = url;
};
reader.onerror = () => {
console.error('Failed to read sprite image file:', file.name);
};
reader.readAsDataURL(file);
};
const processImageFiles = async (files: File[]) => {
for (const f of files) addSprite(f);
};
const addLayer = (name?: string) => {
const l = createEmptyLayer(name || `Layer ${layers.value.length + 1}`);
layers.value.push(l);
activeLayerId.value = l.id;
};
const removeLayer = (id: string) => {
if (layers.value.length === 1) return;
const idx = layers.value.findIndex(l => l.id === id);
if (idx === -1) return;
layers.value.splice(idx, 1);
if (activeLayerId.value === id) activeLayerId.value = layers.value[0].id;
};
const moveLayer = (id: string, direction: 'up' | 'down') => {
const idx = layers.value.findIndex(l => l.id === id);
if (idx === -1) return;
if (direction === 'up' && idx > 0) {
const [l] = layers.value.splice(idx, 1);
layers.value.splice(idx - 1, 0, l);
}
if (direction === 'down' && idx < layers.value.length - 1) {
const [l] = layers.value.splice(idx, 1);
layers.value.splice(idx + 1, 0, l);
}
};
return {
layers,
visibleLayers,
activeLayerId,
activeLayer,
columns,
getMaxDimensions,
updateSpritePosition,
updateSpriteInLayer,
updateSpriteCell,
removeSprite,
replaceSprite,
addSprite,
processImageFiles,
alignSprites,
addLayer,
removeLayer,
moveLayer,
hasSprites,
};
};
export const getMaxDimensionsAcrossLayers = (layers: Layer[]) => {
const sprites = layers.flatMap(l => (l.visible ? l.sprites : []));
return getMaxDimensionsSingle(sprites);
};

View File

@@ -0,0 +1,21 @@
import type { Sprite } from '@/types/sprites';
import { getMaxDimensions } from './useSprites';
/**
* Calculate negative spacing to add to top-left of cells.
* Uses half the available space so spacing is equal on all sides.
*/
export function calculateNegativeSpacing(sprites: Sprite[], enabled: boolean): number {
if (!enabled || sprites.length === 0) return 0;
const { maxWidth, maxHeight } = getMaxDimensions(sprites);
const minWidth = Math.min(...sprites.map(s => s.width));
const minHeight = Math.min(...sprites.map(s => s.height));
// Available space is the gap between cell size and smallest sprite
const availableWidth = maxWidth - minWidth;
const availableHeight = maxHeight - minHeight;
// Use half to balance spacing equally on all sides
return Math.floor(Math.min(availableWidth, availableHeight) / 2);
}

71
src/composables/useSEO.ts Normal file
View File

@@ -0,0 +1,71 @@
import { useHead } from '@vueuse/head';
export interface SEOMetaData {
title: string;
description: string;
image?: string;
url?: string;
type?: 'website' | 'article';
author?: string;
publishedTime?: string;
modifiedTime?: string;
keywords?: string;
}
const SITE_NAME = 'Spritesheet Generator';
const SITE_URL = 'https://spritesheetgenerator.online';
const DEFAULT_IMAGE = '/og-image.png';
export function useSEO(metadata: SEOMetaData) {
const fullTitle = metadata.title.includes(SITE_NAME) ? metadata.title : `${metadata.title} - ${SITE_NAME}`;
const fullUrl = metadata.url ? `${SITE_URL}${metadata.url}` : SITE_URL;
const imageUrl = metadata.image ? `${SITE_URL}${metadata.image}` : `${SITE_URL}${DEFAULT_IMAGE}`;
const metaTags: any[] = [
// Primary Meta Tags
{ name: 'title', content: fullTitle },
{ name: 'description', content: metadata.description },
{ name: 'robots', content: 'index, follow' },
// Open Graph / Facebook
{ property: 'og:type', content: metadata.type || 'website' },
{ property: 'og:url', content: fullUrl },
{ property: 'og:title', content: fullTitle },
{ property: 'og:description', content: metadata.description },
{ property: 'og:image', content: imageUrl },
{ property: 'og:site_name', content: SITE_NAME },
// Twitter
{ name: 'twitter:card', content: 'summary_large_image' },
{ name: 'twitter:url', content: fullUrl },
{ name: 'twitter:title', content: fullTitle },
{ name: 'twitter:description', content: metadata.description },
{ name: 'twitter:image', content: imageUrl },
];
// Add article-specific meta tags
if (metadata.type === 'article') {
if (metadata.author) {
metaTags.push({ property: 'article:author', content: metadata.author });
}
if (metadata.publishedTime) {
metaTags.push({ property: 'article:published_time', content: metadata.publishedTime });
}
if (metadata.modifiedTime) {
metaTags.push({ property: 'article:modified_time', content: metadata.modifiedTime });
}
}
// Add keywords if provided
if (metadata.keywords) {
metaTags.push({ name: 'keywords', content: metadata.keywords });
}
useHead({
title: fullTitle,
meta: metaTags,
link: [{ rel: 'canonical', href: fullUrl }],
});
}

View File

@@ -0,0 +1,283 @@
import { ref, watch, onUnmounted } from 'vue';
import type { Sprite } from '../types/sprites';
export const useSprites = () => {
const sprites = ref<Sprite[]>([]);
const columns = ref(4);
// Clamp and coerce columns to a safe range [1..10]
watch(columns, val => {
const num = typeof val === 'number' ? val : parseInt(String(val));
const safe = Number.isFinite(num) && num >= 1 ? Math.min(num, 10) : 1;
if (safe !== columns.value) columns.value = safe;
});
const updateSpritePosition = (id: string, x: number, y: number) => {
const i = sprites.value.findIndex(s => s.id === id);
if (i !== -1) {
sprites.value[i].x = Math.floor(x);
sprites.value[i].y = Math.floor(y);
}
};
const alignSprites = (position: 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom') => {
if (!sprites.value.length) return;
const { maxWidth, maxHeight } = getMaxDimensions(sprites.value);
sprites.value = sprites.value.map(sprite => {
let x = sprite.x;
let y = sprite.y;
switch (position) {
case 'left':
x = 0;
break;
case 'center':
x = Math.floor((maxWidth - sprite.width) / 2);
break;
case 'right':
x = Math.floor(maxWidth - sprite.width);
break;
case 'top':
y = 0;
break;
case 'middle':
y = Math.floor((maxHeight - sprite.height) / 2);
break;
case 'bottom':
y = Math.floor(maxHeight - sprite.height);
break;
}
return { ...sprite, x: Math.floor(x), y: Math.floor(y) };
});
triggerForceRedraw();
};
const updateSpriteCell = (id: string, newIndex: number) => {
const currentIndex = sprites.value.findIndex(s => s.id === id);
if (currentIndex === -1 || currentIndex === newIndex) return;
const next = [...sprites.value];
if (newIndex < sprites.value.length) {
const moving = { ...next[currentIndex] };
const target = { ...next[newIndex] };
next[currentIndex] = target;
next[newIndex] = moving;
} else {
const [moved] = next.splice(currentIndex, 1);
next.splice(newIndex, 0, moved);
}
sprites.value = next;
};
const removeSprite = (id: string) => {
const i = sprites.value.findIndex(s => s.id === id);
if (i === -1) return;
const s = sprites.value[i];
revokeIfBlob(s.url);
sprites.value.splice(i, 1);
};
const replaceSprite = (id: string, file: File) => {
const i = sprites.value.findIndex(s => s.id === id);
if (i === -1) return;
const old = sprites.value[i];
revokeIfBlob(old.url);
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
const next: Sprite = {
id: old.id,
file,
img,
url,
width: img.width,
height: img.height,
x: old.x,
y: old.y,
};
const arr = [...sprites.value];
arr[i] = next;
sprites.value = arr;
};
img.onerror = () => {
console.error('Failed to load replacement image:', file.name);
};
img.src = url;
};
reader.onerror = () => {
console.error('Failed to read replacement image file:', file.name);
};
reader.readAsDataURL(file);
};
const addSprite = (file: File) => {
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
const s: Sprite = {
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
};
sprites.value = [...sprites.value, s];
};
img.onerror = () => {
console.error('Failed to load new sprite image:', file.name);
};
img.src = url;
};
reader.onerror = () => {
console.error('Failed to read sprite image file:', file.name);
};
reader.readAsDataURL(file);
};
const addSpriteWithResize = (file: File) => {
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
const { maxWidth, maxHeight } = getMaxDimensions(sprites.value);
const newSprite: Sprite = {
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
};
const newMaxWidth = Math.max(maxWidth, img.width);
const newMaxHeight = Math.max(maxHeight, img.height);
if (img.width > maxWidth || img.height > maxHeight) {
sprites.value = sprites.value.map(sprite => {
let newX = sprite.x;
let newY = sprite.y;
if (img.width > maxWidth) {
const relativeX = maxWidth > 0 ? sprite.x / maxWidth : 0;
newX = Math.floor(relativeX * newMaxWidth);
newX = Math.max(0, Math.min(newX, newMaxWidth - sprite.width));
}
if (img.height > maxHeight) {
const relativeY = maxHeight > 0 ? sprite.y / maxHeight : 0;
newY = Math.floor(relativeY * newMaxHeight);
newY = Math.max(0, Math.min(newY, newMaxHeight - sprite.height));
}
return { ...sprite, x: newX, y: newY };
});
}
sprites.value = [...sprites.value, newSprite];
triggerForceRedraw();
};
img.onerror = () => {
console.error('Failed to load new sprite image:', file.name);
};
img.src = url;
};
reader.onerror = () => {
console.error('Failed to read sprite image file:', file.name);
};
reader.readAsDataURL(file);
};
const processImageFiles = (files: File[]) => {
Promise.all(
files.map(
file =>
new Promise<Sprite>((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
resolve({
id: crypto.randomUUID(),
file,
img,
url,
width: img.width,
height: img.height,
x: 0,
y: 0,
});
};
img.onerror = () => reject(new Error(`Failed to load image: ${file.name}`));
img.src = url;
};
reader.onerror = () => reject(new Error(`Failed to read file: ${file.name}`));
reader.readAsDataURL(file);
})
)
)
.then(newSprites => {
sprites.value = [...sprites.value, ...newSprites];
})
.catch(err => {
console.error('Error processing image files:', err);
});
};
onUnmounted(() => {
sprites.value.forEach(s => revokeIfBlob(s.url));
});
return {
sprites,
columns,
updateSpritePosition,
alignSprites,
updateSpriteCell,
removeSprite,
replaceSprite,
addSprite,
addSpriteWithResize,
processImageFiles,
};
};
export const getMaxDimensions = (arr: Sprite[] | Readonly<Sprite[]>): { maxWidth: number; maxHeight: number } => {
let maxWidth = 0;
let maxHeight = 0;
arr.forEach(s => {
if (s.width > maxWidth) maxWidth = s.width;
if (s.height > maxHeight) maxHeight = s.height;
});
return { maxWidth, maxHeight };
};
export const revokeIfBlob = (url?: string) => {
if (url && url.startsWith('blob:')) {
try {
URL.revokeObjectURL(url);
} catch {}
}
};
export const triggerForceRedraw = () => {
setTimeout(() => {
window.dispatchEvent(new Event('forceRedraw'));
}, 0);
};

View File

@@ -0,0 +1,200 @@
import { useHead } from '@vueuse/head';
const SITE_URL = 'https://spritesheetgenerator.online';
const SITE_NAME = 'Spritesheet Generator';
export interface BlogPostSchema {
title: string;
description: string;
author: string;
datePublished: string;
dateModified?: string;
image: string;
url: string;
}
export interface BreadcrumbItem {
name: string;
url: string;
}
export interface FAQItem {
question: string;
answer: string;
}
export function useStructuredData() {
// Organization Schema
const addOrganizationSchema = () => {
const schema = {
'@context': 'https://schema.org',
'@type': 'Organization',
name: SITE_NAME,
url: SITE_URL,
logo: `${SITE_URL}/og-image.png`,
description: 'Free online tool to create spritesheets for game development',
sameAs: ['https://gitea.adhd.sh/root/spritesheet-generator', 'https://discord.gg/JTev3nzeDa'],
};
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify(schema),
},
],
});
};
// WebSite Schema
const addWebSiteSchema = () => {
const schema = {
'@context': 'https://schema.org',
'@type': 'WebSite',
name: SITE_NAME,
url: SITE_URL,
description: 'Create professional spritesheets for your game development projects',
potentialAction: {
'@type': 'SearchAction',
target: `${SITE_URL}/blog?search={search_term_string}`,
'query-input': 'required name=search_term_string',
},
};
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify(schema),
},
],
});
};
// BlogPosting Schema
const addBlogPostSchema = (post: BlogPostSchema) => {
const schema = {
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: post.title,
description: post.description,
image: `${SITE_URL}${post.image}`,
author: {
'@type': 'Person',
name: post.author,
},
publisher: {
'@type': 'Organization',
name: SITE_NAME,
logo: {
'@type': 'ImageObject',
url: `${SITE_URL}/og-image.png`,
},
},
datePublished: post.datePublished,
dateModified: post.dateModified || post.datePublished,
mainEntityOfPage: {
'@type': 'WebPage',
'@id': `${SITE_URL}${post.url}`,
},
};
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify(schema),
},
],
});
};
// Breadcrumb Schema
const addBreadcrumbSchema = (items: BreadcrumbItem[]) => {
const schema = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: items.map((item, index) => ({
'@type': 'ListItem',
position: index + 1,
name: item.name,
item: `${SITE_URL}${item.url}`,
})),
};
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify(schema),
},
],
});
};
// Blog List Schema
const addBlogListSchema = (posts: BlogPostSchema[]) => {
const schema = {
'@context': 'https://schema.org',
'@type': 'Blog',
name: `${SITE_NAME} Blog`,
description: 'Latest articles about sprite sheet generation and game development',
url: `${SITE_URL}/blog`,
blogPost: posts.map(post => ({
'@type': 'BlogPosting',
headline: post.title,
description: post.description,
image: `${SITE_URL}${post.image}`,
author: {
'@type': 'Person',
name: post.author,
},
datePublished: post.datePublished,
url: `${SITE_URL}${post.url}`,
})),
};
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify(schema),
},
],
});
};
// FAQ Schema
const addFAQSchema = (faqs: FAQItem[]) => {
const schema = {
'@context': 'https://schema.org',
'@type': 'FAQPage',
mainEntity: faqs.map(faq => ({
'@type': 'Question',
name: faq.question,
acceptedAnswer: {
'@type': 'Answer',
text: faq.answer,
},
})),
};
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify(schema),
},
],
});
};
return {
addOrganizationSchema,
addWebSiteSchema,
addBlogPostSchema,
addBreadcrumbSchema,
addBlogListSchema,
addFAQSchema,
};
}

View File

@@ -0,0 +1,83 @@
import { ref, computed } from 'vue';
export interface ZoomOptionsStep {
min: number;
max: number;
step: number;
initial?: number;
}
export interface ZoomOptionsAllowed {
allowedValues: number[];
initial?: number;
}
export type ZoomOptions = ZoomOptionsStep | ZoomOptionsAllowed;
function isStepOptions(options: ZoomOptions): options is ZoomOptionsStep {
return 'step' in options;
}
export function useZoom(options: ZoomOptions) {
const initial = options.initial ?? (isStepOptions(options) ? 1 : (options.allowedValues[1] ?? options.allowedValues[0]));
const zoom = ref(initial);
const zoomPercent = computed(() => Math.round(zoom.value * 100));
const increase = () => {
if (isStepOptions(options)) {
zoom.value = Math.min(options.max, zoom.value + options.step);
} else {
const currentIndex = options.allowedValues.indexOf(zoom.value);
if (currentIndex < options.allowedValues.length - 1) {
zoom.value = options.allowedValues[currentIndex + 1];
} else if (currentIndex === -1) {
// Find the nearest higher value
const higher = options.allowedValues.find(v => v > zoom.value);
if (higher !== undefined) {
zoom.value = higher;
}
}
}
};
const decrease = () => {
if (isStepOptions(options)) {
zoom.value = Math.max(options.min, zoom.value - options.step);
} else {
const currentIndex = options.allowedValues.indexOf(zoom.value);
if (currentIndex > 0) {
zoom.value = options.allowedValues[currentIndex - 1];
} else if (currentIndex === -1) {
// Find the nearest lower value
const lower = [...options.allowedValues].reverse().find(v => v < zoom.value);
if (lower !== undefined) {
zoom.value = lower;
}
}
}
};
const reset = () => {
zoom.value = initial;
};
const setZoom = (value: number) => {
if (isStepOptions(options)) {
zoom.value = Math.max(options.min, Math.min(options.max, value));
} else {
// Snap to nearest allowed value
const nearest = options.allowedValues.reduce((prev, curr) => (Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev));
zoom.value = nearest;
}
};
return {
zoom,
zoomPercent,
increase,
decrease,
reset,
setZoom,
};
}

View File

@@ -1,11 +1,21 @@
import { Buffer } from 'buffer';
// @ts-ignore
window.Buffer = Buffer;
import './assets/main.css'; import './assets/main.css';
import { createApp } from 'vue'; import { createApp } from 'vue';
import { createPinia } from 'pinia'; import { createPinia } from 'pinia';
import { createHead } from '@vueuse/head';
import App from './App.vue'; import App from './App.vue';
import router from './router';
const app = createApp(App); const app = createApp(App);
const head = createHead();
app.use(createPinia()); app.use(createPinia());
app.use(router);
app.use(head);
app.mount('#app'); app.mount('#app');

52
src/router/index.ts Normal file
View File

@@ -0,0 +1,52 @@
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutUs.vue'),
},
{
path: '/contact',
name: 'contact',
component: () => import('../views/Contact.vue'),
},
{
path: '/privacy-policy',
name: 'privacy-policy',
component: () => import('../views/PrivacyPolicy.vue'),
},
{
path: '/faq',
name: 'faq',
component: () => import('../views/FAQ.vue'),
},
{
path: '/blog',
name: 'blog-overview',
component: () => import('../views/BlogOverview.vue'),
},
{
path: '/blog/:slug',
name: 'blog-detail',
component: () => import('../views/BlogDetail.vue'),
},
],
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
return { top: 0 };
}
},
});
export default router;

View File

@@ -3,6 +3,12 @@ import { ref, watch } from 'vue';
const pixelPerfect = ref(true); const pixelPerfect = ref(true);
const darkMode = ref(false); const darkMode = ref(false);
const negativeSpacingEnabled = ref(false);
const backgroundColor = ref('transparent');
const manualCellSizeEnabled = ref(false);
const manualCellWidth = ref(64);
const manualCellHeight = ref(64);
const checkerboardEnabled = ref(false);
// Initialize dark mode from localStorage or system preference // Initialize dark mode from localStorage or system preference
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
@@ -51,12 +57,54 @@ export const useSettingsStore = defineStore('settings', () => {
darkMode.value = value; darkMode.value = value;
} }
function toggleNegativeSpacing() {
negativeSpacingEnabled.value = !negativeSpacingEnabled.value;
}
function setBackgroundColor(color: string) {
backgroundColor.value = color;
}
function toggleManualCellSize() {
manualCellSizeEnabled.value = !manualCellSizeEnabled.value;
}
function setManualCellWidth(width: number) {
manualCellWidth.value = Math.max(1, Math.floor(width));
}
function setManualCellHeight(height: number) {
manualCellHeight.value = Math.max(1, Math.floor(height));
}
function setManualCellSize(width: number, height: number) {
setManualCellWidth(width);
setManualCellHeight(height);
}
function toggleCheckerboard() {
checkerboardEnabled.value = !checkerboardEnabled.value;
}
return { return {
pixelPerfect, pixelPerfect,
darkMode, darkMode,
negativeSpacingEnabled,
backgroundColor,
manualCellSizeEnabled,
manualCellWidth,
manualCellHeight,
checkerboardEnabled,
togglePixelPerfect, togglePixelPerfect,
setPixelPerfect, setPixelPerfect,
toggleDarkMode, toggleDarkMode,
setDarkMode, setDarkMode,
toggleNegativeSpacing,
setBackgroundColor,
toggleManualCellSize,
setManualCellWidth,
setManualCellHeight,
setManualCellSize,
toggleCheckerboard,
}; };
}); });

26
src/types/sprites.ts Normal file
View File

@@ -0,0 +1,26 @@
export interface Sprite {
id: string;
file: File;
img: HTMLImageElement;
url: string;
width: number;
height: number;
x: number;
y: number;
}
export interface SpriteFile {
file: File;
x: number;
y: number;
width: number;
height: number;
}
export interface Layer {
id: string;
name: string;
sprites: Sprite[];
visible: boolean;
locked: boolean;
}

38
src/views/AboutUs.vue Normal file
View File

@@ -0,0 +1,38 @@
<script setup lang="ts">
import { useSEO } from '../composables/useSEO';
import { useStructuredData } from '../composables/useStructuredData';
const { addBreadcrumbSchema } = useStructuredData();
// Set SEO synchronously
useSEO({
title: 'About Us - Our Mission & Story',
description: 'Learn about Spritesheet Generator, a free tool designed to help game developers and artists streamline their workflow with optimized spritesheet creation.',
url: '/about',
type: 'website',
keywords: 'about spritesheet generator, game development tools, open source sprite editor',
});
addBreadcrumbSchema([
{ name: 'Home', url: '/' },
{ name: 'About Us', url: '/about' },
]);
</script>
<template>
<div class="w-full">
<div class="bg-white/80 dark:bg-gray-900/80 backdrop-blur-md rounded-3xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 p-8 sm:p-12">
<h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900 dark:text-white mb-6">About Us</h1>
<div class="space-y-6">
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">Welcome to Spritesheet Generator, a tool designed to help game developers and artists streamline their workflow.</p>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">
Our mission is to provide a simple, powerful, and free tool for creating optimized spritesheets directly in your browser. Whether you are an indie developer, a hobbyist, or part of a large studio, we hope this tool makes your life easier.
</p>
<div class="space-y-3">
<h3 class="text-xl font-bold text-gray-900 dark:text-white">Our story</h3>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">This project started as a small utility for personal game jams and has grown into a full-featured spritesheet packer. We believe in open source and community-driven development.</p>
</div>
</div>
</div>
</div>
</template>

152
src/views/BlogDetail.vue Normal file
View File

@@ -0,0 +1,152 @@
<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useBlog, type BlogPost } from '../composables/useBlog';
import { useHead } from '@vueuse/head';
import { marked } from 'marked';
const route = useRoute();
const router = useRouter();
const { getPost } = useBlog();
const post = ref<BlogPost | undefined>(undefined);
const renderedContent = ref('');
const slug = computed(() => route.params.slug as string);
// Reactive SEO data that updates when post loads
const pageTitle = computed(() => (post.value ? `${post.value.title} - Spritesheet Generator` : 'Blog Post - Spritesheet Generator'));
const pageDescription = computed(() => post.value?.description || 'Read our latest article about spritesheet generation and game development.');
const pageImage = computed(() => (post.value?.image ? `https://spritesheetgenerator.online${post.value.image}` : 'https://spritesheetgenerator.online/og-image.png'));
const pageUrl = computed(() => `https://spritesheetgenerator.online/blog/${slug.value}`);
const keywords = computed(() => post.value?.keywords || 'sprite sheet, game development, blog');
// Dynamic meta tags using reactive computed values
useHead({
title: pageTitle,
meta: [
{ name: 'title', content: pageTitle },
{ name: 'description', content: pageDescription },
{ name: 'keywords', content: keywords },
{ name: 'robots', content: 'index, follow' },
// Open Graph
{ property: 'og:type', content: 'article' },
{ property: 'og:url', content: pageUrl },
{ property: 'og:title', content: pageTitle },
{ property: 'og:description', content: pageDescription },
{ property: 'og:image', content: pageImage },
{ property: 'og:site_name', content: 'Spritesheet Generator' },
{ property: 'article:author', content: computed(() => post.value?.author || 'streetshadow') },
{ property: 'article:published_time', content: computed(() => post.value?.date || '') },
// Twitter
{ name: 'twitter:card', content: 'summary_large_image' },
{ name: 'twitter:url', content: pageUrl },
{ name: 'twitter:title', content: pageTitle },
{ name: 'twitter:description', content: pageDescription },
{ name: 'twitter:image', content: pageImage },
],
link: [{ rel: 'canonical', href: pageUrl }],
script: computed(() => {
const scripts = [];
// Breadcrumb schema
scripts.push({
type: 'application/ld+json',
children: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: [
{
'@type': 'ListItem',
position: 1,
name: 'Home',
item: 'https://spritesheetgenerator.online/',
},
{
'@type': 'ListItem',
position: 2,
name: 'Blog',
item: 'https://spritesheetgenerator.online/blog',
},
{
'@type': 'ListItem',
position: 3,
name: post.value?.title || 'Article',
item: pageUrl.value,
},
],
}),
});
// Blog post schema
if (post.value) {
scripts.push({
type: 'application/ld+json',
children: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'BlogPosting',
headline: post.value.title,
description: post.value.description,
image: `https://spritesheetgenerator.online${post.value.image}`,
author: {
'@type': 'Person',
name: post.value.author || 'streetshadow',
},
publisher: {
'@type': 'Organization',
name: 'Spritesheet Generator',
logo: {
'@type': 'ImageObject',
url: 'https://spritesheetgenerator.online/og-image.png',
},
},
datePublished: post.value.date,
dateModified: post.value.date,
mainEntityOfPage: {
'@type': 'WebPage',
'@id': pageUrl.value,
},
}),
});
}
return scripts;
}),
});
onMounted(async () => {
post.value = await getPost(slug.value);
if (post.value) {
renderedContent.value = await marked(post.value.content);
} else {
router.push({ name: 'blog-overview' });
}
});
</script>
<template>
<div class="w-full">
<div v-if="post">
<RouterLink :to="{ name: 'blog-overview' }" class="inline-flex items-center text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white mb-6 transition-colors" title="Return to blog overview" aria-label="Navigate back to blog overview page">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
Back to overview
</RouterLink>
<h1 class="text-4xl font-bold mb-4 text-gray-900 dark:text-white">{{ post.title }}</h1>
<p class="text-gray-600 dark:text-gray-400 text-sm mb-8">{{ post.date }}</p>
<!-- Image is intentionally omitted here as per requirements -->
<div class="prose max-w-none" v-html="renderedContent"></div>
</div>
<div v-else class="text-center py-12">
<p class="text-xl text-gray-600 dark:text-gray-400">Loading...</p>
</div>
</div>
</template>

View File

@@ -0,0 +1,48 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useBlog, type BlogPost } from '../composables/useBlog';
import { useSEO } from '../composables/useSEO';
import { useStructuredData } from '../composables/useStructuredData';
import { RouterLink } from 'vue-router';
const { getPosts } = useBlog();
const { addBreadcrumbSchema } = useStructuredData();
const posts = ref<BlogPost[]>([]);
// Set SEO meta tags synchronously
useSEO({
title: 'Blog - Latest Articles on Spritesheet Generation',
description: 'Explore our latest articles about sprite sheet generation, game development, pixel art, and sprite animation techniques.',
url: '/blog',
type: 'website',
keywords: 'sprite sheet blog, game development articles, pixel art tutorials, sprite animation',
});
// Add breadcrumb synchronously
addBreadcrumbSchema([
{ name: 'Home', url: '/' },
{ name: 'Blog', url: '/blog' },
]);
onMounted(async () => {
posts.value = await getPosts();
});
</script>
<template>
<div class="w-full">
<h1 class="text-4xl font-bold mb-8 text-gray-900 dark:text-white">Blog</h1>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
<article v-for="post in posts" :key="post.slug" class="bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow duration-300 flex flex-col h-full">
<RouterLink :to="{ name: 'blog-detail', params: { slug: post.slug } }" class="flex flex-col h-full" :title="`Read more: ${post.title}`" :aria-label="`Read full blog post: ${post.title}`">
<img :src="post.image" :alt="post.title" class="w-full h-48 object-cover" loading="lazy" decoding="async" />
<div class="p-6 flex-1 flex flex-col">
<h2 class="text-xl font-bold mb-2 text-gray-900 dark:text-white line-clamp-2">{{ post.title }}</h2>
<p class="text-gray-600 dark:text-gray-400 text-xs mb-3">{{ post.date }}</p>
<p class="text-gray-700 dark:text-gray-300 text-sm line-clamp-3 flex-1">{{ post.description }}</p>
</div>
</RouterLink>
</article>
</div>
</div>
</template>

62
src/views/Contact.vue Normal file
View File

@@ -0,0 +1,62 @@
<script setup lang="ts">
import { useSEO } from '../composables/useSEO';
import { useStructuredData } from '../composables/useStructuredData';
const { addBreadcrumbSchema } = useStructuredData();
// Set SEO synchronously
useSEO({
title: 'Contact Us - Get in Touch',
description: "Contact the Spritesheet Generator team. Join our Discord community or report bugs and contribute on Gitea. We'd love to hear from you!",
url: '/contact',
type: 'website',
keywords: 'contact spritesheet generator, support, discord, gitea',
});
addBreadcrumbSchema([
{ name: 'Home', url: '/' },
{ name: 'Contact', url: '/contact' },
]);
</script>
<template>
<div class="w-full">
<div class="bg-white/80 dark:bg-gray-900/80 backdrop-blur-md rounded-3xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 p-8 sm:p-12">
<h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900 dark:text-white mb-6">Contact Us</h1>
<div class="space-y-6">
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">We'd love to hear from you! Whether you have a question, feedback, or just want to say hi, feel free to reach out.</p>
<div class="flex flex-col gap-4 mt-8">
<a
href="https://discord.gg/JTev3nzeDa"
target="_blank"
rel="noopener noreferrer"
class="flex items-center gap-3 p-4 bg-gray-100 dark:bg-gray-800 rounded-xl hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors no-underline"
title="Join our Discord community"
aria-label="Join Discord server"
>
<i class="fab fa-discord text-2xl text-[#5865F2]"></i>
<div>
<div class="font-bold text-gray-900 dark:text-white">Join our Discord</div>
<div class="text-sm text-gray-600 dark:text-gray-400">Chat with the community and developers</div>
</div>
</a>
<a
href="https://gitea.adhd.sh/root/spritesheet-generator"
target="_blank"
rel="noopener noreferrer"
class="flex items-center gap-3 p-4 bg-gray-100 dark:bg-gray-800 rounded-xl hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors no-underline"
title="View source code and report bugs"
aria-label="View source code repository"
>
<i class="fab fa-github text-2xl text-gray-900 dark:text-white"></i>
<div>
<div class="font-bold text-gray-900 dark:text-white">Source Code</div>
<div class="text-sm text-gray-600 dark:text-gray-400">Report bugs or contribute on Gitea</div>
</div>
</a>
</div>
</div>
</div>
</div>
</template>

106
src/views/FAQ.vue Normal file
View File

@@ -0,0 +1,106 @@
<script setup lang="ts">
import { useSEO } from '../composables/useSEO';
import { useStructuredData } from '../composables/useStructuredData';
const { addFAQSchema, addBreadcrumbSchema } = useStructuredData();
// Set SEO synchronously
useSEO({
title: 'FAQ - Frequently Asked Questions',
description: 'Find answers to common questions about the Spritesheet Generator. Learn about supported formats, export options, and how to use the tool effectively.',
url: '/faq',
type: 'website',
keywords: 'faq, spritesheet generator help, questions, support, documentation',
});
addBreadcrumbSchema([
{ name: 'Home', url: '/' },
{ name: 'FAQ', url: '/faq' },
]);
const faqs = [
{
question: 'What is a sprite sheet generator?',
answer: 'A sprite sheet generator is a tool that combines multiple images into a single file. Our sprite maker online simplifies the process of making a sprite sheet, allowing you to create a sprite sheet for games and websites instantly.',
},
{
question: 'How do I create a sprite sheet from images?',
answer: 'To create a sprite sheet, simply drag and drop your files into our images to sprite sheet converter. We support various formats, making it easy to turn PNG to sprite sheet or use our gif to sprite sheet converter.',
},
{
question: 'Can I use this as a 2D sprite generator for games?',
answer: 'Yes! This tool acts as a powerful 2D sprite generator. Whether you need a character sprite sheet generator, an FNF sprite generator, or just a general sprite image generator, our tool handles the packing efficiently.',
},
{
question: 'Do you support GIF to sprite sheet conversion?',
answer: 'Absolutely. You can turn gif into sprite sheet layouts easily. Our tool creates a clean sprite strip or sprite grid from your animations, functioning as a comprehensive image to sprite animation tool.',
},
{
question: 'Is there a specific sprite sheet template?',
answer: 'No fixed sprite sheet template is needed. Our image sprite generator automatically arranges your uploads. It works as a flexible sprite converter for all your needs.',
},
{
question: 'How does the PNG to sprite conversion work?',
answer: 'Our PNG to sprite feature is simple. Upload your images, and the sprite sheet converter stitches them together. It is the easiest way to image to sprite converter workflows.',
},
{
question: 'Can I create a sprite sheet for Unity or Godot?',
answer: 'Yes, you can create a sprite sheet compatible with major game engines like Unity, Godot, and Unreal Engine. Our sprite sheet converter exports standard formats that work seamlessly with these tools.',
},
{
question: 'What is the difference between a sprite strip and a sprite grid?',
answer: 'A sprite strip arranges images in a single horizontal or vertical row, ideal for simple animations. A sprite grid arranges images in rows and columns, which is better for larger collections or character sprite sheets.',
},
{
question: 'Can I preview the image to sprite animation?',
answer: 'Yes, our tool includes a preview feature. After using the image to sprite animation function, you can play back the sequence to ensure your animation looks perfect before exporting.',
},
{
question: 'Does this sprite maker online work on mobile devices?',
answer: 'Our sprite maker online is fully responsive and works on most modern mobile devices and tablets, allowing you to create sprite sheets on the go.',
},
{
question: 'How many images can I add to the images to sprite sheet converter?',
answer: 'There is no hard limit on the number of images you can add to the images to sprite sheet converter, but performance may vary depending on your device and the size of the images.',
},
];
addFAQSchema(faqs);
</script>
<template>
<div class="w-full">
<div class="bg-white/80 dark:bg-gray-900/80 backdrop-blur-md rounded-3xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 p-8 sm:p-12">
<h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900 dark:text-white mb-6">Frequently Asked Questions</h1>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed mb-10">Got questions? We've got answers. If you can't find what you're looking for, feel free to <router-link to="/contact" class="text-blue-600 dark:text-blue-400 hover:underline">contact us</router-link>.</p>
<div class="space-y-6">
<details
v-for="(faq, index) in faqs"
:key="index"
class="group bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden transition-all duration-300 hover:shadow-md open:bg-white dark:open:bg-gray-800 open:shadow-lg open:border-blue-200 dark:open:border-blue-900"
>
<summary class="flex items-center justify-between p-6 cursor-pointer list-none">
<h3 class="text-lg font-bold text-gray-900 dark:text-white pr-4">{{ faq.question }}</h3>
<span class="transform transition-transform duration-300 group-open:rotate-180 text-gray-500 dark:text-gray-400">
<i class="fas fa-chevron-down"></i>
</span>
</summary>
<div class="px-6 pb-6 text-gray-700 dark:text-gray-300 leading-relaxed border-t border-gray-100 dark:border-gray-700/50 pt-4">
{{ faq.answer }}
</div>
</details>
</div>
</div>
</div>
</template>
<style scoped>
/* Remove default triangle for details/summary */
details > summary {
list-style: none;
}
details > summary::-webkit-details-marker {
display: none;
}
</style>

53
src/views/HomeView.seo.ts Normal file
View File

@@ -0,0 +1,53 @@
import { useSEO } from '../composables/useSEO';
import { useStructuredData } from '../composables/useStructuredData';
import { useHead } from '@vueuse/head';
export function useHomeViewSEO() {
const { addOrganizationSchema, addWebSiteSchema } = useStructuredData();
// Set page SEO synchronously
useSEO({
title: 'Spritesheet Generator - Create Game Spritesheets Online',
description: 'Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview.',
url: '/',
type: 'website',
keywords: 'spritesheet generator, sprite sheet maker, game development, pixel art, sprite animation, game assets, 2D game tools',
});
// Add organization schema
addOrganizationSchema();
// Add website schema
addWebSiteSchema();
// Add SoftwareApplication schema
useHead({
script: [
{
type: 'application/ld+json',
children: JSON.stringify({
'@context': 'https://schema.org',
'@type': 'SoftwareApplication',
name: 'Spritesheet Generator',
applicationCategory: 'DesignApplication',
offers: {
'@type': 'Offer',
price: '0',
priceCurrency: 'USD',
},
operatingSystem: 'Web Browser',
description: 'Free online tool to create spritesheets for game development. Upload sprites, arrange them, and export as a spritesheet with animation preview.',
url: 'https://spritesheetgenerator.online',
screenshot: 'https://spritesheetgenerator.online/og-image.png',
featureList: ['Free sprite editor', 'Automatic spritesheet generation', 'Customizable grid layouts', 'Animation preview', 'Cross-platform compatibility', 'Zero installation required', 'Batch processing', 'Multiple export formats (PNG, JPG, GIF, ZIP, JSON)'],
browserRequirements: 'Requires JavaScript. Requires HTML5.',
aggregateRating: {
'@type': 'AggregateRating',
ratingValue: '4.8',
ratingCount: '127',
},
}),
},
],
});
}

434
src/views/HomeView.vue Normal file
View File

@@ -0,0 +1,434 @@
<template>
<main class="flex flex-col flex-1 bg-white/80 dark:bg-gray-900/80 backdrop-blur-md rounded-3xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 transition-all duration-300" :class="{ 'lg:overflow-hidden': layers.some(l => l.sprites.length) }">
<!-- Welcome state -->
<div v-if="!layers.some(l => l.sprites.length)" class="p-6 sm:p-10">
<div class="mb-8">
<div class="flex items-center justify-between gap-4 mb-1">
<p class="text-2xl font-bold text-gray-800 dark:text-gray-100">Upload sprites or single image</p>
<a href="https://ko-fi.com/X8X416D44P" target="_blank" rel="noopener noreferrer">
<img height="36" style="border: 0px; height: 36px" src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" alt="Buy Me a Coffee at ko-fi.com" />
</a>
</div>
<p class="text-sm text-gray-600 dark:text-gray-400">Drag and drop images or import from JSON</p>
</div>
<file-uploader @upload-sprites="handleSpritesUpload" />
<div class="mt-10">
<div class="prose prose-lg dark:prose-invert max-w-none">
<div>
<h1 class="text-2xl font-bold text-gray-800 dark:text-gray-100 mb-4">Welcome to Spritesheet generator</h1>
<p class="text-gray-700 dark:text-gray-300 mb-4">Create spritesheets for your game development and animation projects with our completely free, open-source Spritesheet generator.</p>
<p class="text-gray-700 dark:text-gray-300 mb-6">This powerful online tool lets you upload individual sprite images and automatically arrange them into optimized sprite sheets with customizable layouts - perfect for indie developers, animators, and studios of any size.</p>
<h3 class="text-2xl font-bold text-gray-800 dark:text-gray-100 mb-4">Key features of this sprite editor</h3>
<ul class="text-gray-700 dark:text-gray-300 mb-6 space-y-2 list-disc">
<li><strong>Free sprite editor</strong>: Edit, organize, and optimize your game sprites directly in your browser</li>
<li><strong>Automatic spritesheet generation</strong>: Convert multiple PNG, JPG, or GIF images into efficient sprite atlases</li>
<li><strong>Customizable grid layouts</strong>: Adjust spacing, padding, and arrangement for pixel-perfect results</li>
<li><strong>Animation preview</strong>: Test your sprite animations before exporting</li>
<li><strong>Cross-platform compatibility</strong>: Works with Unity, Godot, Phaser, Pygame, and other game engines</li>
<li><strong>Zero installation required</strong>: No downloads - use our web-based sprite sheet maker instantly</li>
<li><strong>Batch processing</strong>: Upload and process multiple sprites simultaneously</li>
<li><strong>Export options</strong>: Download spritesheet as PNG, JPG, GIF, ZIP or JSON.</li>
</ul>
<div>
<h4 class="text-xl font-bold text-gray-800 dark:text-gray-100 mb-4 flex items-center gap-2">
<i class="fas fa-play-circle text-gray-800 dark:text-gray-200"></i>
How it works
</h4>
<video controls playsinline class="w-full rounded-lg shadow-lg border border-gray-200 dark:border-gray-700" title="Spritesheet generator tutorial" aria-label="Spritesheet generator tutorial">
<source src="@/assets/demo.mp4" type="video/mp4" />
</video>
</div>
</div>
</div>
</div>
</div>
<!-- Two-column layout: Left controls, Right preview -->
<div v-if="layers.some(l => l.sprites.length)" class="flex flex-col flex-1 lg:grid lg:grid-cols-[380px_1fr] xl:grid-cols-[420px_1fr] lg:overflow-hidden">
<!-- Left sidebar - Controls -->
<div class="p-6 bg-gray-50/50 dark:bg-gray-900/30 border-b lg:border-b-0 lg:border-r border-gray-200 dark:border-gray-700 lg:overflow-y-auto lg:overflow-x-auto">
<div class="space-y-8">
<!-- Upload Section -->
<section>
<div class="flex items-center justify-between mb-3">
<h3 class="flex items-center gap-2 text-base font-bold text-gray-800 dark:text-gray-100">
<i class="text-sm text-gray-700 dark:text-gray-300 fas fa-upload"></i>
Upload
</h3>
<button @click="openJSONImportDialog" class="btn btn-dark btn-sm" data-rybbit-event="import-json">
<i class="text-xs fas fa-file-import"></i>
<span>JSON</span>
</button>
</div>
<button
class="w-full p-6 text-center border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl hover:border-gray-500 dark:hover:border-gray-400 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-all cursor-pointer focus:outline-none focus:ring-2 focus:ring-gray-500 group"
@click="openFileDialog"
>
<i class="fas fa-plus-circle text-3xl text-gray-400 dark:text-gray-500 group-hover:text-gray-600 dark:group-hover:text-gray-300 mb-3 transition-colors"></i>
<p class="text-sm font-medium text-gray-600 dark:text-gray-400 group-hover:text-gray-900 dark:group-hover:text-gray-200 transition-colors">Add sprites</p>
</button>
<input ref="uploadInput" type="file" multiple accept="image/*" class="hidden" @change="handleUploadChange" />
<input ref="jsonFileInput" type="file" accept=".json,application/json" class="hidden" @change="handleJSONFileChange" />
</section>
<!-- Layers -->
<section>
<div class="flex items-center justify-between mb-3">
<h3 class="flex items-center gap-2 text-base font-bold text-gray-800 dark:text-gray-100">
<i class="text-sm text-gray-700 dark:text-gray-300 fas fa-layer-group"></i>
Layers
</h3>
<button @click="addLayer()" class="btn btn-dark btn-sm">
<i class="text-xs fas fa-plus"></i>
<span>Add</span>
</button>
</div>
<div class="space-y-2">
<div
v-for="layer in layers"
:key="layer.id"
class="flex items-center gap-2 px-3 py-2 bg-white dark:bg-gray-800 border rounded-lg transition-all"
:class="[layer.id === activeLayerId ? 'border-gray-800 ring-1 ring-gray-800 dark:border-gray-400 dark:ring-gray-400' : 'border-gray-200 dark:border-gray-700', !layer.visible ? 'opacity-50' : '']"
>
<button @click.stop="layer.visible = !layer.visible" class="btn btn-ghost btn-icon-sm rounded" :title="layer.visible ? 'Hide layer' : 'Show layer'">
<i :class="layer.visible ? 'text-sm text-gray-800 dark:text-gray-200 fas fa-eye' : 'text-sm text-gray-400 dark:text-gray-500 fas fa-eye-slash'"></i>
</button>
<input
v-if="editingLayerId === layer.id"
type="text"
v-model="editingLayerName"
@blur="finishEditingLayer"
@keyup.enter="finishEditingLayer"
@keyup.esc="cancelEditingLayer"
class="flex-1 px-2 py-1 text-sm border border-gray-800 dark:border-gray-400 dark:bg-gray-700 dark:text-gray-100 rounded outline-none focus:ring-2 focus:ring-gray-800 dark:focus:ring-gray-400"
ref="layerNameInput"
@click.stop
/>
<button v-else @click="activeLayerId = layer.id" class="flex-1 px-2 py-1 text-sm font-medium text-left rounded transition-all cursor-pointer" :class="layer.id === activeLayerId ? 'text-gray-900 dark:text-gray-100' : 'text-gray-700 dark:text-gray-300'">
{{ layer.name }}
<span v-if="layer.sprites.length" class="ml-1 text-xs opacity-60">({{ layer.sprites.length }})</span>
</button>
<button v-if="editingLayerId !== layer.id" @click="startEditingLayer(layer.id, layer.name)" class="btn btn-ghost btn-icon-xs rounded" title="Rename">
<i class="text-xs text-gray-600 dark:text-gray-400 fas fa-pen"></i>
</button>
<button @click="moveLayer(layer.id, 'up')" class="btn btn-ghost btn-icon-xs rounded" title="Move up">
<i class="text-xs text-gray-600 dark:text-gray-400 fas fa-chevron-up"></i>
</button>
<button @click="moveLayer(layer.id, 'down')" class="btn btn-ghost btn-icon-xs rounded" title="Move down">
<i class="text-xs text-gray-600 dark:text-gray-400 fas fa-chevron-down"></i>
</button>
<button v-if="layers.length > 1" @click="removeLayer(layer.id)" class="btn btn-danger btn-icon-xs rounded" title="Delete">
<i class="text-xs fas fa-trash"></i>
</button>
</div>
</div>
</section>
<!-- Grid Settings -->
<section>
<h3 class="flex items-center gap-2 mb-3 text-base font-bold text-gray-800 dark:text-gray-100">
<i class="text-sm text-gray-700 dark:text-gray-300 fas fa-th"></i>
Grid
</h3>
<div class="space-y-3">
<div class="flex items-center justify-between px-3 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
<label for="columns" class="text-sm font-medium text-gray-700 dark:text-gray-200">Columns</label>
<input id="columns" type="number" v-model.number="columns" min="1" max="10" class="input-field w-16" />
</div>
<div class="px-3 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg">
<label class="flex items-center justify-between mb-2 cursor-pointer">
<span class="text-sm font-medium text-gray-700 dark:text-gray-200">Manual size</span>
<input type="checkbox" v-model="settingsStore.manualCellSizeEnabled" class="w-4 h-4 rounded" />
</label>
<div v-if="settingsStore.manualCellSizeEnabled" class="flex items-center gap-1.5 mt-2">
<input type="number" v-model.number="settingsStore.manualCellWidth" min="1" max="2048" class="input-field w-full min-w-0" placeholder="W" />
<span class="flex-shrink-0 text-gray-500 dark:text-gray-400">×</span>
<input type="number" v-model.number="settingsStore.manualCellHeight" min="1" max="2048" class="input-field w-full min-w-0" placeholder="H" />
</div>
<div v-else class="mt-1 text-xs font-mono text-gray-500 dark:text-gray-400 break-words">{{ cellSize.width }} × {{ cellSize.height }}px</div>
</div>
</div>
</section>
<!-- Alignment -->
<section>
<h3 class="flex items-center gap-2 mb-3 text-base font-bold text-gray-800 dark:text-gray-100">
<i class="text-sm text-gray-700 dark:text-gray-300 fas fa-align-center"></i>
Align
</h3>
<div class="grid grid-cols-3 gap-2">
<button @click="alignSprites('left')" class="btn btn-secondary btn-sm" title="Left">
<i class="fas fa-arrow-left"></i>
</button>
<button @click="alignSprites('center')" class="btn btn-secondary btn-sm" title="Center">
<i class="fas fa-arrows-left-right"></i>
</button>
<button @click="alignSprites('right')" class="btn btn-secondary btn-sm" title="Right">
<i class="fas fa-arrow-right"></i>
</button>
<button @click="alignSprites('top')" class="btn btn-secondary btn-sm" title="Top">
<i class="fas fa-arrow-up"></i>
</button>
<button @click="alignSprites('middle')" class="btn btn-secondary btn-sm" title="Middle">
<i class="fas fa-arrows-up-down"></i>
</button>
<button @click="alignSprites('bottom')" class="btn btn-secondary btn-sm" title="Bottom">
<i class="fas fa-arrow-down"></i>
</button>
</div>
</section>
<!-- Export -->
<section>
<h3 class="flex items-center gap-2 mb-3 text-base font-bold text-gray-800 dark:text-gray-100">
<i class="text-sm text-gray-700 dark:text-gray-300 fas fa-download"></i>
Export
</h3>
<div class="grid grid-cols-2 gap-2">
<button @click="downloadSpritesheet" class="btn btn-dark btn-sm" data-rybbit-event="download-spritesheet">
<i class="fas fa-image"></i>
<span>PNG</span>
</button>
<button @click="exportSpritesheetJSON" class="btn btn-dark btn-sm" data-rybbit-event="export-json">
<i class="fas fa-file-code"></i>
<span>JSON</span>
</button>
<button @click="openGifFpsModal" class="btn btn-dark btn-sm" data-rybbit-event="download-gif">
<i class="fas fa-film"></i>
<span>GIF</span>
</button>
<button @click="downloadAsZip" class="btn btn-dark btn-sm" data-rybbit-event="download-zip">
<i class="fas fa-file-archive"></i>
<span>ZIP</span>
</button>
</div>
</section>
</div>
</div>
<!-- Right panel - Tabs -->
<div class="flex flex-col overflow-hidden">
<!-- Tab Navigation -->
<div class="bg-gray-50/50 dark:bg-gray-900/30 border-b border-gray-200 dark:border-gray-700">
<div class="flex gap-1 p-2">
<button
@click="activeTab = 'canvas'"
class="border-gray-600 border"
:class="['flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all cursor-pointer', activeTab === 'canvas' ? 'bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 shadow-sm' : 'text-gray-600 dark:text-gray-400 hover:bg-white/50 dark:hover:bg-gray-800/50']"
>
<i class="fas fa-th"></i>
<span>Canvas</span>
</button>
<button
@click="activeTab = 'preview'"
class="border-gray-600 border"
:class="['flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-all cursor-pointer', activeTab === 'preview' ? 'bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 shadow-sm' : 'text-gray-600 dark:text-gray-400 hover:bg-white/50 dark:hover:bg-gray-800/50']"
data-rybbit-event="preview-animation"
>
<i class="fas fa-play"></i>
<span>Preview</span>
</button>
</div>
</div>
<!-- Tab Content -->
<div class="p-6 lg:flex-1 lg:overflow-auto">
<div v-if="activeTab === 'canvas'">
<sprite-canvas :layers="layers" :active-layer-id="activeLayerId" :columns="columns" @update-sprite="updateSpritePosition" @update-sprite-cell="updateSpriteCell" @remove-sprite="removeSprite" @replace-sprite="replaceSprite" @add-sprite="addSprite" />
</div>
<div v-if="activeTab === 'preview'">
<sprite-preview :layers="layers" :active-layer-id="activeLayerId" :columns="columns" @update-sprite="updateSpritePosition" @update-sprite-in-layer="updateSpriteInLayer" />
</div>
</div>
</div>
</div>
<SpritesheetSplitter :is-open="isSpritesheetSplitterOpen" :image-url="spritesheetImageUrl" :image-file="spritesheetImageFile" @close="closeSpritesheetSplitter" @split="handleSplitSpritesheet" />
<GifFpsModal :is-open="isGifFpsModalOpen" @close="closeGifFpsModal" @confirm="downloadAsGif" :default-fps="10" />
</main>
</template>
<script setup lang="ts">
import { ref, toRef, computed } from 'vue';
import FileUploader from '@/components/FileUploader.vue';
import SpriteCanvas from '@/components/SpriteCanvas.vue';
import SpritePreview from '@/components/SpritePreview.vue';
import SpritesheetSplitter from '@/components/SpritesheetSplitter.vue';
import GifFpsModal from '@/components/GifFpsModal.vue';
import { useExportLayers } from '@/composables/useExportLayers';
import { useLayers } from '@/composables/useLayers';
import { getMaxDimensionsAcrossLayers } from '@/composables/useLayers';
import { useSettingsStore } from '@/stores/useSettingsStore';
import { calculateNegativeSpacing } from '@/composables/useNegativeSpacing';
import { useHomeViewSEO } from './HomeView.seo';
import type { SpriteFile } from '@/types/sprites';
// Initialize SEO
useHomeViewSEO();
const settingsStore = useSettingsStore();
const { layers, visibleLayers, activeLayer, activeLayerId, columns, updateSpritePosition, updateSpriteInLayer, updateSpriteCell, removeSprite, replaceSprite, addSprite, processImageFiles, alignSprites, addLayer, removeLayer, moveLayer } = useLayers();
const { downloadSpritesheet, exportSpritesheetJSON, importSpritesheetJSON, downloadAsGif, downloadAsZip } = useExportLayers(
layers,
columns,
toRef(settingsStore, 'negativeSpacingEnabled'),
activeLayerId,
toRef(settingsStore, 'backgroundColor'),
toRef(settingsStore, 'manualCellSizeEnabled'),
toRef(settingsStore, 'manualCellWidth'),
toRef(settingsStore, 'manualCellHeight')
);
const getCellSize = () => {
if (!visibleLayers.value.length) return { width: 0, height: 0 };
if (settingsStore.manualCellSizeEnabled) {
return { width: settingsStore.manualCellWidth, height: settingsStore.manualCellHeight };
}
const { maxWidth, maxHeight } = getMaxDimensionsAcrossLayers(visibleLayers.value);
const allSprites = visibleLayers.value.flatMap(l => l.sprites);
const negativeSpacing = calculateNegativeSpacing(allSprites, settingsStore.negativeSpacingEnabled);
return { width: maxWidth + negativeSpacing, height: maxHeight + negativeSpacing };
};
const cellSize = computed(getCellSize);
const activeTab = ref<'canvas' | 'preview'>('canvas');
const isSpritesheetSplitterOpen = ref(false);
const isGifFpsModalOpen = ref(false);
const uploadInput = ref<HTMLInputElement | null>(null);
const jsonFileInput = ref<HTMLInputElement | null>(null);
const spritesheetImageUrl = ref('');
const spritesheetImageFile = ref<File | null>(null);
const editingLayerId = ref<string | null>(null);
const editingLayerName = ref('');
const layerNameInput = ref<HTMLInputElement | null>(null);
const handleSpritesUpload = async (files: File[]) => {
const jsonFile = files.find(file => file.type === 'application/json' || file.name.endsWith('.json'));
if (jsonFile) {
await handleJSONImport(jsonFile);
return;
}
if (files.length === 1 && files[0].type.startsWith('image/')) {
const file = files[0];
const reader = new FileReader();
reader.onload = e => {
const url = e.target?.result as string;
const img = new Image();
img.onload = () => {
if (confirm('This looks like it might be a spritesheet. Would you like to split it into individual sprites?')) {
spritesheetImageUrl.value = url;
spritesheetImageFile.value = file;
isSpritesheetSplitterOpen.value = true;
return;
}
processImageFiles([file]);
};
img.onerror = () => {
console.error('Failed to load image:', file.name);
};
img.src = url;
};
reader.onerror = () => {
console.error('Failed to read image file:', file.name);
};
reader.readAsDataURL(file);
return;
}
processImageFiles(files);
};
const handleJSONImport = async (jsonFile: File) => {
try {
await importSpritesheetJSON(jsonFile);
} catch (error) {
console.error('Error importing JSON:', error);
alert('Failed to import JSON file. Please check the file format.');
}
};
const closeSpritesheetSplitter = () => {
isSpritesheetSplitterOpen.value = false;
if (spritesheetImageUrl.value && spritesheetImageUrl.value.startsWith('blob:')) {
try {
URL.revokeObjectURL(spritesheetImageUrl.value);
} catch {}
}
spritesheetImageUrl.value = '';
spritesheetImageFile.value = null;
};
const openGifFpsModal = () => {
if (!visibleLayers.value.some(l => l.sprites.length > 0)) {
alert('Please upload or import sprites before generating a GIF.');
return;
}
isGifFpsModalOpen.value = true;
};
const closeGifFpsModal = () => {
isGifFpsModalOpen.value = false;
};
const handleSplitSpritesheet = (spriteFiles: SpriteFile[]) => {
processImageFiles(spriteFiles.map(s => s.file));
};
const openJSONImportDialog = () => {
jsonFileInput.value?.click();
};
const handleJSONFileChange = async (event: Event) => {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
await handleJSONImport(input.files[0]);
input.value = '';
}
};
const openFileDialog = () => {
uploadInput.value?.click();
};
const handleUploadChange = async (event: Event) => {
const input = event.target as HTMLInputElement;
if (input.files && input.files.length > 0) {
await handleSpritesUpload(Array.from(input.files));
input.value = '';
}
};
const startEditingLayer = (layerId: string, currentName: string) => {
editingLayerId.value = layerId;
editingLayerName.value = currentName;
// Focus the input on next tick
setTimeout(() => {
layerNameInput.value?.focus();
layerNameInput.value?.select();
}, 0);
};
const finishEditingLayer = () => {
if (editingLayerId.value && editingLayerName.value.trim()) {
const layer = layers.value.find(l => l.id === editingLayerId.value);
if (layer) {
layer.name = editingLayerName.value.trim();
}
}
editingLayerId.value = null;
editingLayerName.value = '';
};
const cancelEditingLayer = () => {
editingLayerId.value = null;
editingLayerName.value = '';
};
</script>

View File

@@ -0,0 +1,56 @@
<script setup lang="ts">
import { useSEO } from '../composables/useSEO';
import { useStructuredData } from '../composables/useStructuredData';
const { addBreadcrumbSchema } = useStructuredData();
// Set SEO synchronously
useSEO({
title: 'Privacy Policy - Your Data Protection',
description: 'Read our privacy policy. Spritesheet Generator is a client-side tool that does not collect personal data or upload your images to our servers.',
url: '/privacy-policy',
type: 'website',
keywords: 'privacy policy, data protection, client-side processing',
});
addBreadcrumbSchema([
{ name: 'Home', url: '/' },
{ name: 'Privacy Policy', url: '/privacy-policy' },
]);
</script>
<template>
<div class="w-full">
<div class="bg-white/80 dark:bg-gray-900/80 backdrop-blur-md rounded-3xl shadow-2xl border border-gray-200/50 dark:border-gray-700/50 p-8 sm:p-12">
<h1 class="text-3xl sm:text-4xl font-extrabold text-gray-900 dark:text-white mb-6">Privacy Policy</h1>
<div class="space-y-6">
<p class="text-sm text-gray-500 dark:text-gray-400 mb-8">Last updated: November 26, 2025</p>
<div class="space-y-3">
<h3 class="text-xl font-bold text-gray-900 dark:text-white">1. Introduction</h3>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">We respect your privacy. This Spritesheet Generator is a client-side tool, meaning your images are processed directly in your browser and are not uploaded to our servers.</p>
</div>
<div class="space-y-3">
<h3 class="text-xl font-bold text-gray-900 dark:text-white">2. Data collection</h3>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">We do not collect any personal data or uploaded images. All processing happens locally on your device.</p>
</div>
<div class="space-y-3">
<h3 class="text-xl font-bold text-gray-900 dark:text-white">3. Local storage</h3>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">We use your browser's Local Storage to save your preferences (such as dark mode and grid settings) to improve your experience.</p>
</div>
<div class="space-y-3">
<h3 class="text-xl font-bold text-gray-900 dark:text-white">4. Third-Party services</h3>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">We do not use third-party services for analytics.</p>
</div>
<div class="space-y-3">
<h3 class="text-xl font-bold text-gray-900 dark:text-white">5. Contact</h3>
<p class="text-gray-700 dark:text-gray-300 leading-relaxed">If you have any questions about this Privacy Policy, please contact us via our Discord server.</p>
</div>
</div>
</div>
</div>
</template>

View File

@@ -68,5 +68,7 @@ export default {
}), }),
}, },
}, },
plugins: [], plugins: [
require('@tailwindcss/typography'),
],
} }