Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

javascript - google chrome extension canvas icon

I am trying to set the extension icon to a canvas image. I can't seem to get it to set. I just want to get the basics working and expand from there. I can set the icon with an image in the file structure but I want to be able to dynamically update the text later.

I tried a few ways to get chrome.browserAction.setIcon to set to no avail. I hope it is not something simple I am missing.

Thanks

//chrome.browserAction.setIcon({imageData: draw()});
draw();

function draw() {
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext('2d');
  canvas.width = 19;
  canvas.height = 19;
  context.fillStyle = "#262626";
  context.fillRect(0, 0, 19, 19);
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.font = "11px Arial";
  context.fillText("69F", 8, 8);
  chrome.browserAction.setIcon({
    imageData: context.getImageData(0, 0, 19, 19)
  });
  //return context.getImageData(0, 0, 19, 19);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code works correctly under the assumption document.getElementById('canvas') returns an element. If you're running this in a background page defined as a script, it will be empty.

You don't actually need to have an element in the DOM for it to work. Just create a new element just for this.

Also, note that you're writing text using the same color as the background; so it's invisible.

Putting it together (and nudging the coordinates a bit):

draw();

function draw() {
  var canvas = document.createElement('canvas'); // Create the canvas
  canvas.width = 19;
  canvas.height = 19;

  var context = canvas.getContext('2d');
  context.fillStyle = "#262626";
  context.fillRect(0, 0, 19, 19);

  context.fillStyle = "#FFFFFF";
  context.textAlign = "center";
  context.textBaseline = "middle";
  context.font = "11px Arial";
  context.fillText("69F", 8, 8);

  chrome.browserAction.setIcon({
    imageData: context.getImageData(0, 0, 19, 19)
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...