检查画布上的数据并相应地应用类

时间:2017-10-16 12:23:24

标签: jquery css canvas

我正在使用一个名为jqscribble的jQuery插件来绘制画布。如果画布没有任何内容,我想灰度图标。正如插件文档中所提到的,我可以使用if ($('#draw').data('jqScribble').blank) { $("#pencil").css("filter" , "grayscale(100%)"); } else { $("#pencil").css("filter" , "grayscale(0%)"); } 进行检查,我正在使用它:

function getGender() {
    var yourGender = prompt('Enter your gender (M / F)');
    var choice = yourGender;

if (choice = 'M' || 'F') {
    return choice;
} else
    do {
        var yourGender = prompt('Enter your gender (M / F)');
    }
    while (choice != 'M' || 'F') {

    }
}

这会在加载时使我的图标灰显,但在画布上绘图无效。有没有办法可以连续检查这个?

2 个答案:

答案 0 :(得分:1)

更好的检查方法是监控画布的点击/触摸,假设这些是绘制到画布上的唯一方法(如果绘制了外部数据,您也可以随时使用这些功能)。

  • 如果检测到点击或触摸,请标记画布“污染”
  • 清除(或保存或其他条件)时,清除污渍标记

通过这种方式,您无需始终从画布中提取数据,这对于某些类型的检查具有巨大的开销,例如拉动数据uri并将其与表示空白画布的数据进行比较。

var rect = c.getBoundingClientRect(),
    dx = rect.left, dy = rect.top,
    isTainted = false,
    isDown = false,
    ctx = c.getContext("2d"),
    save = document.getElementById("save"),
    clr = document.getElementById("clr");

c.onmousedown = function(e) {
  isDown = isTainted = true;    // mark canvas tainted
  status();                     // update ghosted button
  draw(e);                      // draw something...
};
window.onmousemove = function(e) {if (isDown) draw(e)};
window.onmouseup = function() {isDown = false};

clr.onclick = function() {
  isTainted = false;           // clear tainted flag (in this case)
  status();
  c.width = c.width;
};

function draw(e) {ctx.fillRect(e.clientX - dx - 1, e.clientY - dy - 1, 2, 2)}
function status() {save.disabled = !isTainted}
#c {background:#ddd}
<button id=save disabled>Save</button>
<button id=clr>Clear</button>
<div><canvas id=c width=600 height=600></canvas></div>

答案 1 :(得分:1)

每次单击画布时,使用事件侦听器运行代码。

Game.js:48 Uncaught TypeError: $(...).tooltip is not a function
    at Game.init (Game.js:48)
    at Object.<anonymous> (init.js:6)
    at Object.<anonymous> (init.js:7)
    at __webpack_require__ (bootstrap aa1ecbe…:678)

或者,既然你问过,你也可以用setInterval()每秒运行代码,例如:

$("canvas").mousedown( function() {
    if ($('#draw').data('jqScribble').blank) {
        $("#pencil").css("filter" , "grayscale(100%)");
    } else {
        $("#pencil").css("filter" , "grayscale(0%)");
    }
});

只需更改末尾的数字即可调整间隔时间(以毫秒为单位)。