Skip to content

Instantly share code, notes, and snippets.

@drhayes
Last active July 7, 2016 18:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drhayes/ff53b78cceea1cc1b211 to your computer and use it in GitHub Desktop.
Save drhayes/ff53b78cceea1cc1b211 to your computer and use it in GitHub Desktop.
Scaled, pixel-perfect drawing in Phaser using a second canvas
var scaledDraw = require('../util/scaledDraw');
Main.prototype.init = function(levelName) {
scaledDraw.init.call(this);
this.scale.setResizeCallback(scaledDraw.resize, this);
};
Main.prototype.render = function() {
scaledDraw.render.call(this);
};
'use strict';
var pixel = {
scale: 2,
canvas: null,
context: null,
width: 0,
height: 0
};
var scaledDraw = module.exports = {
// Called from within context of a Stage.
init: function() {
this.game.canvas.style['display'] = 'none';
scaledDraw.resize.call(this, this.scale, {
width: window.innerWidth,
height: window.innerHeight
});
},
// Called from within a context of a Stage.
render: function() {
pixel.context.drawImage(this.game.canvas, 0, 0, this.game.width, this.game.height, 0, 0, pixel.width, pixel.height);
},
resize: function(scale, parentBounds) {
var w = parentBounds.width / 320;
var h = parentBounds.height / 240;
var s = Math.max(1, Math.min(w, h));
pixel.scale = s;
if (pixel.canvas) {
pixel.canvas.remove();
}
pixel.canvas = Phaser.Canvas.create(this.game.width * pixel.scale, this.game.height * pixel.scale);
pixel.context = pixel.canvas.getContext('2d');
Phaser.Canvas.addToDOM(pixel.canvas);
Phaser.Canvas.setSmoothingEnabled(pixel.context, false);
pixel.width = pixel.canvas.width;
pixel.height = pixel.canvas.height;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment