1

数字だけで毎日更新されるChrome拡張機能を作成しようとしています(1を引く)

私はすでにクロム拡張の背景として数字を印刷させていますが、今は毎日数字を変えようとしています。私は4つのファイルを持っています:

background.js
icon_19.png
jquery.js
manifest.json

キャンバスを使用して拡張機能の背景を設定するには、最初に画像を用意する必要があるため、icon_19.pngが必要です。

jquery.jsは単なる JavaScript ライブラリです。私はそれを含めます。

マニフェスト.json:

{
  "manifest_version": 2,

  "name": "Countdown",
  "description": "This extension countdowns to my death.",
  "version": "1.0",
  "background": {
    "scripts":["background.js"]
  },
  "browser_action": {
    "default_title": "Countdown",
    "default_popup": "countdown.html"
  }
}

background.js:

var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var myDeath = new Date();
myDeath.setMonth(7);
myDeath.setDate(16);
var canvas = document.createElement('canvas');
canvas.width = 19;
canvas.height = 19;
var ctx = canvas.getContext('2d');
var start = 18;

ctx.font='20px Arial';

setInterval(function() {
  ctx.clearRect(0,0,19,19);
  ctx.fillText(start, 0, 19, 19);
  start--;
  chrome.browserAction.setIcon({
    imageData: ctx.getImageData(0, 0, 19, 19)
  })  
}, 1000);

これが何をするかというと、番号 (開始) をクロム拡張の背景として出力します。その後、1 秒ごとにカウントダウンを開始します。それも機能します。に達するまで、翌日ごとに-1しか減算されないようにする方法が必要myDeathです。数字を毎日1ずつ変える方法を知っている人はいますか? chromeを開いたときに1日1回数字が下がってほしい。前もって感謝します!!:)

4

1 に答える 1

1

いくつかのメモ:

  • 更新間隔を長くする必要があります。1日1秒をさわやかにする意味はありません。私は 12 時間ごとに設定していますが、好きなだけ変更できます。
  • 日付差の計算は、繰り返し呼び出すことができるように、独自の関数にする必要があります。これにより、死亡日データがそれを利用するコードから分離されるため、コードの保守が少し簡単になります。
  • 保守性のために、死亡日の構成を独自のオブジェクトに分離しました。
  • death.month1 ~ 12 の値を保持します。最初のコード コメントを参照してください。
  • death.yearはオプションであり、その引数は関数では必須ではありません。
  • background.js変更の必要性以外には何もありません。

background.js

var death = {
    day: 16,
    month: 8
}
var intervalHours = 12;

function getRemainingDays(d, m, y){
    var today = new Date();
    var myDeath = new Date();
    myDeath.setMonth(m-1); // Month is a range from 0-11; this lets you configure using a range from 1-12
    myDeath.setDate(d);
    if(typeof y !== "undefined"){ // if death.year is not provided, just use the current year
        myDeath.setYear(y);
    }
    return (myDeath-today)/86400000; // (myDeath-today) produces a result in milliseconds, this turns that into days
}

var canvas = document.createElement('canvas');
canvas.width = 19;
canvas.height = 19;
var ctx = canvas.getContext('2d');
ctx.font='20px Arial';

setInterval(function() {
  ctx.clearRect(0,0,19,19);
  ctx.fillText(getRemainingDays(death.day, death.month), 0, 19, 19);
  chrome.browserAction.setIcon({
    imageData: ctx.getImageData(0, 0, 19, 19)
  })  
}, (intervalHours*3600000)); // converts hours to milliseconds
于 2013-07-31T01:37:55.603 に答える