Vla*_*iev 4 javascript google-chrome google-chrome-extension
我正在寻找如何将文本设置为Page Action图标并找到此示例:
window.setInterval(function() {
chrome.pageAction.setIcon({
imageData: draw(10, 0),
tabId: tabId
});
}, 1000);
function draw(starty, startx) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = "icon_16.png"
img.onload = function() {
context.drawImage(img, 0, 2);
}
//context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(255,0,0,1)";
context.fillRect(startx % 19, starty % 19, 10, 10);
context.fillStyle = "white";
context.font = "11px Arial";
context.fillText("3", 0, 19);
return context.getImageData(0, 0, 19, 19);
}
Run Code Online (Sandbox Code Playgroud)
但是在我把eventPage.js它包括在内之后说Uncaught TypeError: Cannot call method 'getContext' of null.然后我用Google搜索了这个错误,发现getContext只有在加载DOM后我才能使用它.所以我将上面的代码包装到jQuery .ready函数中,但结果是一样的.
所以我不知道现在哪里出现错误以及我必须搜索哪种方式.
问题是你的canvas元素是未定义的(并且undefined没有getContext()方法).问题的原因是canvas您的后台页面中没有元素,因此您需要先创建它.
例如:
// Replace that line:
var canvas = document.getElementById('canvas');
// With this line:
var canvas = document.createElement('canvas');
Run Code Online (Sandbox Code Playgroud)
还有一个问题:
该draw()函数在加载图像之前返回(并执行其回调,将图像绘制到画布上).我修改了代码,以确保在加载图像后设置页面操作图像:
chrome.pageAction.onClicked.addListener(setPageActionIcon);
function setPageActionIcon(tab) {
var canvas = document.createElement('canvas');
var img = document.createElement('img');
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 2);
context.fillStyle = "rgba(255,0,0,1)";
context.fillRect(10, 0, 19, 19);
context.fillStyle = "white";
context.font = "11px Arial";
context.fillText("3", 0, 19);
chrome.pageAction.setIcon({
imageData: context.getImageData(0, 0, 19, 19),
tabId: tab.id
});
};
img.src = "icon16.png";
}
Run Code Online (Sandbox Code Playgroud)
根据您的使用方式,可能会有更有效的方法(例如,不必每次都加载图像,但保持加载的实例).
如果有人有兴趣,这是我模仿"原生"Chrome徽章的蹩脚尝试.
| 归档时间: |
|
| 查看次数: |
643 次 |
| 最近记录: |