【NodeJS】png画像を生成する
2021-10-03
久しぶりの記事、表題の通りCanvasを利用して画像を生成し、pngとして保存するメモ
Env.
Node : v12.18.2
SourceCode
早速ソースコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
var fs = require('fs'); var Canvas = require('canvas'); var canvas = Canvas.createCanvas(1920, 1080); var ctx = canvas.getContext('2d'); // 四角形描画 // ctx.fillStyle = 'rgba(0, 255, 255, 1)'; //RGBで入力するとき ctx.fillStyle = hsvToRgb(34, 0.71, 1); //HSVで入力するとき ctx.fillRect(0, 0, 1920, 1080); //塗りつぶす // Base64で出力も行うとき // var base64 = canvas.toDataURL("image/png"); // console.log(base64); const buffer = canvas.toBuffer('image/png') fs.writeFileSync('./test.png', buffer); //Ref: https://qiita.com/hachisukansw/items/633d1bf6baf008e82847 function hsvToRgb(H,S,V) { //https://en.wikipedia.org/wiki/HSL_and_HSV#From_HSV var C = V * S; var Hp = H / 60; var X = C * (1 - Math.abs(Hp % 2 - 1)); var R, G, B; if (0 <= Hp && Hp < 1) {[R,G,B]=[C,X,0]}; if (1 <= Hp && Hp < 2) {[R,G,B]=[X,C,0]}; if (2 <= Hp && Hp < 3) {[R,G,B]=[0,C,X]}; if (3 <= Hp && Hp < 4) {[R,G,B]=[0,X,C]}; if (4 <= Hp && Hp < 5) {[R,G,B]=[X,0,C]}; if (5 <= Hp && Hp < 6) {[R,G,B]=[C,0,X]}; var m = V - C; [R, G, B] = [R+m, G+m, B+m]; R = Math.floor(R * 255); G = Math.floor(G * 255); B = Math.floor(B * 255); return 'rgb(' + [R ,G, B].join(",") + ')'; } |
References
JavaScriptでHSVからRGBに変換
https://qiita.com/hachisukansw/items/633d1bf6baf008e82847