UNPKG

2.08 kBJavaScriptView Raw
1"use strict";
2/** @module buffer */
3
4/**
5 * Make an invisible {@link canvas}.
6 * @param {number} width The width of the canvas
7 * @param {number} height The height of the canvas
8 * @returns {external:canvas} A canvas DOM element
9 * @private
10 */
11function makeCanvas(width, height) {
12 var c = document.createElement("canvas");
13 c.width = width;
14 c.height = height;
15 // when retina support is enabled, context.getImageData() reads from the wrong pixel causing NinePatch to break
16 if (window.ejecta) {
17 c.retinaResolutionEnabled = false;
18 }
19 return c;
20}
21
22/**
23 * Make an invisible canvas buffer, and draw on it.
24 * @param {number} width The width of the buffer
25 * @param {number} height The height of the buffer
26 * @param {drawCallback} drawFun The callback that draws on the buffer
27 * @returns {external:canvas} The drawn buffer
28 */
29function makeBuffer(width, height, drawFun) {
30 var canvas = makeCanvas(width, height);
31 var ctx = canvas.getContext("2d");
32 // when image smoothing is enabled, the image gets blurred and the pixel data isn't correct even when the image shouldn't be scaled which breaks NinePatch
33 if (window.ejecta) {
34 ctx.imageSmoothingEnabled = false;
35 }
36 drawFun(ctx);
37 return canvas;
38}
39
40/**
41 * Make a horizonally-flipped copy of a buffer or image.
42 * @param {external:canvas|external:image} buffer The original image
43 * @return {external:canvas} The flipped buffer
44 */
45function flipBufferHorizontally(buffer) {
46 return makeBuffer(buffer.width, buffer.height, function(context) {
47 context.scale(-1, 1);
48 context.drawImage(buffer, -buffer.width, 0);
49 });
50}
51
52/**
53 * Make a vertically-flipped copy of a buffer or image.
54 * @param {external:canvas|external:image} buffer The original image
55 * @return {external:canvas} The flipped buffer
56 */
57function flipBufferVertically(buffer) {
58 return makeBuffer(buffer.width, buffer.height, function(context) {
59 context.scale(1, -1);
60 context.drawImage(buffer, 0, -buffer.height);
61 });
62}
63
64module.exports = {
65 makeBuffer: makeBuffer,
66 flipBufferHorizontally: flipBufferHorizontally,
67 flipBufferVertically: flipBufferVertically
68};