Изменить цвет фона холста на прозрачный - PullRequest
0 голосов
/ 30 сентября 2019

У меня есть текст под холстом, я хочу показать его, когда стираю фоновый цвет холста. Теперь он красный, когда я написал прозрачный, он не работает. Мне нужно показать этот текст, когда я рисую мышью. Я тоже пытался с rgba, но он не работал.

, пожалуйста, помогите мне, если вы можете

enter code here

var cont = document.getElementById("spots"),      // UI elements
    canvas = document.getElementById("canvas"),
    alpha = document.getElementById("alpha"),
    modes = document.getElementById("modes"),
    ctx = canvas.getContext("2d"),
    isDown = false,                               // defaults
    color = "red";

// set up color palette using a custom "Spot" object
// This will use a callback function when it is clicked, to
// change current color
function Spot(color, cont, callback) {
    var div = document.createElement("div");
    div.style.cssText = "width:50px;height:50px;border:1px solid #000;margin:0 1px 1px 0;background:" + color;
    div.onclick = function() {callback(color)};
    cont.appendChild(div);
}

// add some spot colors to our palette container
new Spot(color, cont, setColor);

// this will set current fill style based on spot clicked
function setColor(c) {ctx.fillStyle = c}

// setup defaults
ctx.fillStyle = color;
ctx.globalAlpha = 1;

// events
canvas.onmousedown = function() {isDown = true};
window.onmouseup = function() {isDown = false};
window.onmousemove = function(e) {
    if (!isDown) return;
    var r = canvas.getBoundingClientRect(),
        x = e.clientX - r.left,
        y = e.clientY - r.top;

    ctx.beginPath();
    ctx.arc(x, y, 25, 0, 2*Math.PI);
    ctx.fill();
};
.main-content{
  position: relative;
  width: 300px;
  height: 300px;
}
.main-text{
  position: absolute;
  right: 0;
  left: 0;
  text-align: center;
  z-index: 8;
  font-size: 35px;
}
#canvas{
  background-color: green;
  position: absolute;
  z-index: 9;
}
<div class="main-content">
    <p class="main-text">You Won!!!</p>
    <canvas id="canvas" width=300 height=300 style="border: 1px solid green;"></canvas>
    <div id="spots"></div>
</div>

Ответы [ 2 ]

0 голосов
/ 30 сентября 2019

Вы на полпути, но есть пара вещей, которые нужно изменить. То, что вы пытаетесь сделать, это изменить внешний вид свойства css через холст, который не работает таким образом. Вы также не можете изменить прозрачность холста, однако есть решения для вашего случая, и это очень просто.

Вам необходимо применить цвет фона к холсту, а затем удалить пиксели, используя точныета же функция рисования, что и у вас, затем вы устанавливаете дополнительное свойство с именем globalCompositeOperation , которое по сути является «BlendMode» в фотошопе.

Итак, вот ваш обновленный код:

var cont = document.getElementById("spots"),      // UI elements
    canvas = document.getElementById("canvas"),
    alpha = document.getElementById("alpha"),
    modes = document.getElementById("modes"),
    ctx = canvas.getContext("2d"),
    isDown = false,                               // defaults
    color = "red";

// set up color palette using a custom "Spot" object
// This will use a callback function when it is clicked, to
// change current color
function Spot(color, cont, callback) {
    var div = document.createElement("div");
    div.style.cssText = "width:50px;height:50px;border:1px solid #000;margin:0 1px 1px 0;background:" + color;
    div.onclick = function() {callback(color)};
    cont.appendChild(div);
}

// add some spot colors to our palette container
//new Spot(color, cont, setColor);

// this will set current fill style based on spot clicked
function setColor(c) {ctx.fillStyle = c}

// setup defaults
ctx.fillStyle = color;
ctx.globalAlpha = 1;
// draw the background
ctx.fillRect(0, 0, 300, 300);
// add the 'blend mode effect'
ctx.globalCompositeOperation = 'destination-out';

// events
canvas.onmousedown = function() {isDown = true};
window.onmouseup = function() {isDown = false};
window.onmousemove = function(e) {
    if (!isDown) return;
    var r = canvas.getBoundingClientRect(),
        x = e.clientX - r.left,
        y = e.clientY - r.top;
    ctx.beginPath();
    ctx.arc(x, y, 25, 0, 2*Math.PI);
    ctx.fill();
};
.main-content{
  position: relative;
  width: 300px;
  height: 300px;
  background: blue;
}
.main-text{
  position: absolute;
  right: 0;
  left: 0;
  text-align: center;
  z-index: 8;
  font-size: 35px
}
#canvas{
  position: absolute;
  z-index: 9;
}
<div class="main-content">
    <p class="main-text">You Won!!!</p>
    <canvas id="canvas" width=300 height=300 style="border: 1px solid green;"></canvas>
    <div id="spots"></div>
</div>

Помимо этого крошечного изменения в JS, я также изменил порядок z-index в CSS. Удачи

0 голосов
/ 30 сентября 2019

Я думаю, вы хотели бы получить что-то вроде решения в фрагменте ниже.

var cont = document.getElementById("spots"), // UI elements
  canvas = document.getElementById("canvas"),
  alpha = document.getElementById("alpha"),
  modes = document.getElementById("modes"),
  ctx = canvas.getContext("2d"),
  isDown = false, // defaults
  color = "green";

// set up color palette using a custom "Spot" object
// This will use a callback function when it is clicked, to
// change current color
function Spot(color, cont, callback) {
  var div = document.createElement("div");
  div.style.cssText = "width:50px;height:50px;border:1px solid #000;margin:0 1px 1px 0;background:" + color;
  div.onclick = function() {
    callback(color)
  };
  cont.appendChild(div);
}

// add some spot colors to our palette container
new Spot(color, cont, setColor);

// this will set current fill style based on spot clicked
function setColor(c) {
  ctx.fillStyle = c
}

// setup defaults
ctx.fillStyle = color;
ctx.globalAlpha = 1;

// create a rectangle using canvas functions, not CSS
// background color.
const createRect = (ctx, width, height) => {
  ctx.fillRect(0, 0, width, height)
}

createRect(ctx, 300, 300)

// events
canvas.onmousedown = function() {
  isDown = true
};
window.onmouseup = function() {
  isDown = false
};
window.onmousemove = function(e) {
  if (!isDown) return;
  var r = canvas.getBoundingClientRect(),
    x = e.clientX - r.left,
    y = e.clientY - r.top;

  // you needed a bit more code here:
  ctx.fillStyle = "rgba(255, 255, 255, 0.5)"

  ctx.save();
  ctx.globalCompositeOperation = 'destination-out';

  ctx.beginPath();
  ctx.arc(x, y, 25, 0, 2 * Math.PI, false);
  ctx.fill();

  ctx.restore();
};
.main-content {
  position: relative;
  width: 300px;
  height: 300px;
}

.main-text {
  position: absolute;
  right: 0;
  left: 0;
  text-align: center;
  z-index: 8;
  font-size: 35px;
}

#canvas {
  /*background-color: green;*/
  position: absolute;
  z-index: 9;
}
<div class="main-content">
  <p class="main-text">You Won!!!</p>
  <canvas id="canvas" width=300 height=300 style="border: 1px solid green;"></canvas>
  <div id="spots"></div>
</div>

О полотнах глобальных композиций: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

...