3

Я пытаюсь реализовать при помощи canvas функционал стирания изображения ластиком. Я создаю canvas и задаю ему background в CSS. Поверх canvas я делаю drawImage png картинки с прозрачностью, к которой я применяю ластик. Мне нужно проверить, стерта ли картинка полностью, то есть полностью ли прозрачный фон, и осуществить дальше какое-то действие.

Мой метод создания канваса, отрисовки png на нем и процесса стирания:

var img = new Image;
var canvas = {};

function createCanvas(parent, width, height) {

    canvas.node = document.createElement('canvas');
    canvas.context = canvas.node.getContext('2d');

    img.onload = function(){
    canvas.context.drawImage(img,200,0,img.width*1.2,img.height*1.2); // Or at whatever offset you like
    };
    img.src = 'raccoon.png';

    canvas.node.width = width || 100;
    canvas.node.height = height || 100;
    parent.appendChild(canvas.node);
    return canvas;
}

function init(container, width, height, fillColor) {
    var canvas = createCanvas(container, width, height);
    var ctx = canvas.context;
    // define a custom fillCircle method
    ctx.fillCircle = function(x, y, radius, fillColor) {
        this.fillStyle = fillColor;
        this.beginPath();
        this.moveTo(x, y);
        this.arc(x, y, radius, 0, Math.PI * 2, false);
        this.fill();
    };
    ctx.clearTo = function(fillColor) {
        ctx.fillStyle = fillColor;
        ctx.fillRect(0, 0, width, height);
    };

    // bind mouse events
    canvas.node.onmousemove = function(e) {
        if (!canvas.isDrawing) {
           return;
        }
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        var radius = 80; // or whatever
        var fillColor = '#000000';
        ctx.globalCompositeOperation = 'destination-out';
        ctx.fillCircle(x, y, radius, fillColor);
    };
    canvas.node.onmousedown = function(e) {
        canvas.isDrawing = true;
    };
    canvas.node.onmouseup = function(e) {
        canvas.isDrawing = false;
        if (isFullyTransparent()) {
            redirect();
        };
    };

}

function isFullyTransparent() {
var d = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
for (var i=3; i < d.length; i+=4)
if (d[i]) 
  return false
return true
}

function redirect() {
    };

var container = document.getElementById('canvas');
init(container, 1024, 768, '');

введите сюда описание изображения

Картинка для примера. Нужен метод, проверяющий, стерт енот полностью или нет.

7
  • неплохо бы еще код, которым изображение стирается 23 окт 2019 в 6:29
  • я изменил ответ 23 окт 2019 в 8:20
  • добавил код в вопрос 24 окт 2019 в 18:29
  • ну Вы не трогаете прозрачность... 24 окт 2019 в 18:38
  • Не совсем понял, где я не трогаю прозрачность? Я разместил пока только свой код, не Ваш. У меня фон, задаваемый в css. Поверх него я кладу png фигурку енота с прозрачностью. Стираю. Нужно проверить, все стерто или нет. 24 окт 2019 в 18:41

1 ответ 1

5

Можно проверить все пиксели на прозрачность при помощи их перебора и поиска не 0 значения:

Рисовать левой кнопкой мыши, стирать - правой

var img = new Image;
var canvas = {};

function createCanvas(parent, width, height) {
    canvas.node = document.createElement('canvas');
    canvas.context = canvas.node.getContext('2d');
    img.onload = function() {
      canvas.context.drawImage(img,0,0,img.width,img.height); 
      canvas.context.globalCompositeOperation = 'destination-out';
    };
    img.crossOrigin = "anonymous";
    img.src = 'https://i.imgur.com/GtBHNPS.png';
    canvas.node.width = width || 100;
    canvas.node.height = height || 100;
    parent.appendChild(canvas.node);
    return canvas;
}

function init(container, width, height, fillColor) {
    var canvas = createCanvas(container, width, height);
    var ctx = canvas.context;
    ctx.fillCircle = function(x, y, radius, fillColor) {
        this.fillStyle = fillColor;
        this.beginPath();
        this.moveTo(x, y);
        this.arc(x, y, radius, 0, Math.PI * 2, false);
        this.fill();
    };
    ctx.clearTo = function(fillColor) {
        ctx.fillStyle = fillColor;
        ctx.fillRect(0, 0, width, height);
    };
    canvas.node.onmousemove = function(e) {
        if (!canvas.isDrawing) 
           return;
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        var radius = 80; 
        var fillColor = '#fff';
        ctx.fillCircle(x, y, radius, fillColor);
    };
    canvas.node.onmousedown = function(e) {
        canvas.isDrawing = true;
    };
    canvas.node.onmouseup = function(e) {
        canvas.isDrawing = false;
        if (isFullyTransparent()) {
            redirect();
        };
    };
}

function isFullyTransparent() {
  var d = canvas.context.getImageData(0, 0, canvas.node.width, canvas.node.height).data;
  for (var i=3; i < d.length; i+=4)
  if (d[i]) 
    return false
  return true
}

function redirect() {
  alert('redirect')
}

init(document.body, 350, 350);
body{
  background: #000a;
}

2
  • Спасибо, интересно. 1-й блок - в код скрипта, второй в CSS, третий - в html-часть. Правильно? А вызываю этот метод вот так? canvas.node.onmouseup = function(e) { canvas.isDrawing = false; if (isFullyTransparent(canvas)) { redirect(); }; }; Пока что не работает. 22 окт 2019 в 19:12
  • @МихаилФогель в целом да, добавьте код в вопрос, а я уточню ответ 22 окт 2019 в 19:16

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.