Generate a high-resolution image using PhaserJS

I've been experimenting with creating graphics using PhaserJS and now I'm looking for a way to export them as high-resolution images or, even better, as vector-based graphics.

Here's an example of the code I've been working on:

var config = {
    width: 800,
    height: 600,
    type: Phaser.WEBGL,
    parent: 'phaser-example',
    scene: {
        create: create
    }
};

var game = new Phaser.Game(config);

function create ()
{
    var graphics = this.add.graphics();

    graphics.fillGradientStyle(0xff0000, 0xff0000, 0x0000ff, 0x0000ff, 1);

    graphics.fillCircle(300, 300, 200);

    graphics.fillGradientStyle(0xff0000, 0xff0000, 0xffff00, 0xffff00, 1);

    graphics.fillCircle(500, 300, 140);
}

Do you have any suggestions on how I can achieve my goal? I'd appreciate any ideas or tips. Thank you!

Answer №1

Utilizing SVG with Phaser may not be straightforward since Phaser relies on HTML5 Canvas (as mentioned by "Orkhan Alikhanov" in the comments).

To extract an image from Phaser, you can follow these steps:

// access the phaser-canvas
let canvas = document.querySelector('canvas');
let dataURL = canvas.toDataURL('image/png');

// initiate the download process
let downloadHelper = document.createElement('a');
downloadHelper.setAttribute('download', 'download.png');
downloadHelper.setAttribute('href', dataURL);
downloadHelper.click();

For high resolution, increase the size of the phaser application (adjust the width and height in the game configuration) to match the desired final resolution.

Note: If you wish to save only a portion of the canvas, refer to this post & answer () which demonstrates how to save sections of the phaser-canvas as a PNG file (using the file-saving library https://github.com/eligrey/FileSaver.js).

However, if you only deal with HTML5 canvas, you could utilize this library to generate SVG. This was referenced in this post and acts as a wrapper for HTML5 canvas, BUT it's incompatible with Phaser. Update: It might function if you are using Phaser.CANVAS. You could inject the context/canvas similarly to this example, into the Phaser config

Check out a demo for creating images from WebGL:
(Link to the documentation)

document.body.style = 'margin:0;';

    var config = {
        type: Phaser.WEBGL,
        width: 536,
        height: 183,
        // ensure this property is set correctly
        preserveDrawingBuffer: true,
        physics: {
            default: 'arcade',
            arcade: {            
                gravity:{ y: 100 },
                debug: true
            }
        },
        scene: {
            create
        },
        banner: false
    }; 

    function create () {
        var graphics = this.add.graphics();

        graphics.fillGradientStyle(0xff0000, 0xff0000, 0x0000ff, 0x0000ff, 1);
        graphics.fillCircle(300, 300, 200);
        graphics.fillGradientStyle(0xff0000, 0xff0000, 0xffff00, 0xffff00, 1);
        graphics.fillCircle(500, 300, 140);
        
        this.input.on('pointerdown', _ => {
        let canvas = document.querySelector('canvas');
    let dataURL = canvas.toDataURL('image/png');

    // begin downloading by triggering the event ....
    let downloadHelper = document.querySelector('#link');
         downloadHelper.setAttribute('download', 'download.png');
         downloadHelper.setAttribute('href', dataURL);
         
        });
    }

    new Phaser.Game(config);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9a828b998f98aad9c4dfdfc4d8">[email protected]</a>/dist/phaser.js"></script>
Right Click and select "Save Link as ..."<br>
<a id="link">DOWNLOAD </a> <br/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

Tips for efficiently updating state in recompose by utilizing setTimeout?

Curious to learn more about recompose, my journey began with a basic component: const timer: React.SFC<MyProps | any> = ({ seconds }) => ( <span>{ seconds }</span> ); I wanted to find a way to pass the seconds prop using recompose, ...

The PHP script's header() function is failing to execute

Recently, I encountered an issue with my JavaScript code that calls a backend PHP script using AJAX. The main function of the AJAX request is to send user login data (username and password) to the PHP script, which in turn queries this information on the S ...

Sending information from Ajax to PHP

Could anyone please explain the script provided above to me? I am attempting to pass the value of $user data so that I can utilize $_REQUEST['user'] within sort.php, but I am encountering difficulties. It seems to be passing in a long URL. $(fun ...

Name of Document (changing from php to ?)

Greetings! Currently, I am utilizing PHP to include the document name as an example. folder/<?phpecho basename(__FILE__, '.' . pathinfo(__FILE__, PATHINFO_EXTENSION));?>_button.png I have observed that using PHP for this purpose and havin ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

Is there a method to ascertain the relative position of a point on a polygon?

Apologies in advance as I might have a hard time wording this question properly, so I'll start by explaining my objective. I'm currently working with JavaScript and Raphael. My goal is to save the position of a point in relation to the four cor ...

What is the best way to handle promises within the context of updating state in React

Recently, I've been working on a React code snippet focused on creating a text input field. onChangeDestination(url, index) { this.setState(prevState => { const rules = [...prevState.rules]; rules[index] = { ...rules[index], url}; ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

Utilizing the Jquery ready method in conjunction with the load function

While utilizing the ready() method to access the DOM, I encountered an issue where jQuery was returning undefined when trying to access an element. Even after nesting the ready() function inside $(window).on("load", function()), there were still instances ...

Using Node.JS to retrieve values of form fields

I am working with Node.js without using any frameworks (specifically without express). Here is my current code snippet: const { headers, method, url } = req; let body = []; req.on('error', (err) => { console.error(err); }).on(&apos ...

I'm looking for a way to connect to my X-UI database using node.js - can anyone

I am looking to develop an app in node.js that will allow me to create my own RESTful APIs using a x-ui Xray graphical management panel. My goal is to be able to handle operations such as creating, editing, and retrieving data through the HTTP protocol. In ...

The use of Physijs and implementing setLinearVelocity for object movement

2-09-2015 - UPDATE: The code provided below is now functional with the use of setLinearVelocity(). If you were facing similar issues, this updated code may help you. Find the original question with the corrected code below... A player object has been deve ...

What is the best way to assign a value to a button in Ionic/Angular?

Is there a way to bind the name and value attributes to a button? I am facing an issue with this and need a solution. I am attempting to achieve the following: <ion-button type="submit" color="primary" style="text-align:center& ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...

Issue with Material-UI Autocomplete: OnChange function causing interference with other functionalities

Handling the Autocomplete component has been a challenge for me, this is my current code snippet: <Autocomplete multiple id="checkboxes-tags-demo" options={ownerOptions2} disableCloseOnSelect filterSelectedOptio ...

Sending values from multiple radio groups in JavaScript can be done by accessing each group individually and extracting

This is an add to cart system. Currently, I am able to send quantity with an ID. However, I also want to send radio group values. How can I achieve this? Here are my codes: product.php <script> jQuery(function ($) { $('.popbutton').on(&a ...