为什么画布的上下文属性不会根据按钮单击而改变?

时间:2016-05-20 23:16:43

标签: javascript google-chrome-extension html5-canvas

我正在创建一个允许用户在网页上绘制的扩展程序。到目前为止,他们有三种选择,用笔,荧光笔画画,或者抹去他们画过的东西。

我遇到的问题是我似乎无法在每个绘图用具之间切换。我有两个文件一起工作;一个popup.js和一个utensils.js

popup.js:

var eventDelegator = document.getElementById("eventDelegate");

eventDelegator.addEventListener("click", function(e){
  var target = e.target;
  chrome.tabs.executeScript(null, {file: "createCanvas.js"});

  if(target.id == "penButton" || target.id == "penPic" || target.id == "penName"){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
      chrome.tabs.sendMessage(tabs[0].id, {button: 'pen'});
    }
    );
  }
  if(target.id == "highlightButton" || target.id == "highlighterName" || target.id == "highlighterPic"){
    //alert("highlighter");
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
      chrome.tabs.sendMessage(tabs[0].id, {button: 'highlighter'});
    }
  );
  }
  /*else if(target.id == "eraserButton"){
    //chrome.tabs.executeScript(null, {file: "Utensils/Eraser.js"});
  }*/
  chrome.tabs.executeScript(null, {file: "Test Files/utensils.js"});

});

utensils.js:

var canvas = document.getElementById("webpageCanvas");
var context = canvas.getContext('2d');

var position = {x: 0, y: 0};
var last = {lastX: 0, lastY: 0};

function main(utensilClicked){
  if(utensilClicked == 'pen'){
    context.lineWidth = 3;
    context.lineJoin = 'round';
    context.lineCap = 'round';
    context.strokeStyle = 'black';
  }
  if(utensilClicked == 'highlighter'){
    context.lineWidth = 20;
    context.lineJoin = 'miter';
    context.lineCap = 'square';
    context.strokeStyle = "rgba(13, 213, 252, .4)";
  }

  function draw(){
    context.beginPath();
    context.moveTo(last.lastX, last.lastY);
    context.lineTo(position.x, position.y);
    context.closePath();
    context.stroke();
  }

  canvas.addEventListener('mousemove', function(e){
    last.lastX = position.x;
    last.lastY = position.y;

    position.x = e.pageX - this.offsetLeft;
    position.y = e.pageY - this.offsetTop;
  }, false);

  canvas.addEventListener('mousedown', function(e){
    //context.beginPath();
    //context.moveTo(position.x, position.y);
    canvas.addEventListener("mousemove", draw, false);
  });

  canvas.addEventListener('mouseup', function(){
    //When the mouse button isn't being held, then it removes the event listener
    canvas.removeEventListener('mousemove', draw, false);
  }, false);
}

chrome.runtime.onMessage.addListener(function(request, sender){
  main(request.button);
});

在一个实例中单击一个按钮时,绘图功能可以正常工作。但是,当单击另一个按钮或单击相同的按钮时,绘图功能将停止。如果我多次单击按钮,如果单击并拖动,我的鼠标光标将变为“无符号”。

我怀疑,按钮点击一遍又一遍地注入utensils.js,但我不知道这是否正确。

Bump#1

0 个答案:

没有答案