пытаюсь добавить фото вместо цвета - PullRequest
0 голосов
/ 03 августа 2020
    (function() {
    // Creates a new canvas element and appends it as a child
    // to the parent element, and returns the reference to
    // the newly created canvas element
  
  
    function createCanvas(parent, width, height) {
      var canvas = {};
      canvas.node = document.createElement('canvas');
      canvas.context = canvas.node.getContext('2d');
      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);
      };
      ctx.clearTo(fillColor || "yel");
  
      // 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 = 40; // or whatever
        var fillColor = '#ff0000';
        ctx.globalCompositeOperation = 'destination-out';
        ctx.fillCircle(x, y, radius, fillColor);
      };
      canvas.node.onmousedown = function(e) {
        canvas.isDrawing = false;
      };
      canvas.node.onmouseup = function(e) {
        canvas.isDrawing = true;
      };
    }
  
    var img = document.createElement("img");
    img.src= "blm.jpg";


    var container = document.getElementById('canvas');

    init(container, window.innerWidth, window.innerHeight, 'img');
  
  })();

Привет, я пытаюсь сделать обложку для своего холста вместо простого черного цвета на моем коде. вместо этого я бы хотел, чтобы мое изображение с именем «blm.jpg» заменило простой черный. Я не знаю, как это сделать. Я новичок в кодировании и был бы очень признателен за любую помощь, которую я могу получить :) Я добавил var img = document 5 строк снизу и 4-ю строку снизу, я не уверен, что это тоже значит.

заранее спасибо за любую помощь :)

1 Ответ

0 голосов
/ 03 августа 2020

Вот простой пример того, как это сделать, я просто рисую сетку поверх фонового изображения

var canvas = document.querySelector("canvas"),
  ctx = canvas.getContext("2d"),
  backgroundImage = document.createElement("img");

backgroundImage.src = "https://openclipart.org/image/400px/svg_to_png/260587/Surreal-Fantastic-Nature.png";

function makeLine(start_x, start_y, end_x, end_y) {
  ctx.moveTo(start_x, start_y);
  ctx.lineTo(end_x, end_y);
}

function drawGrid(val, color) {
  ctx.beginPath();
  ctx.strokeStyle = color;
  for(var i = 0; i <= canvas.height; i += val) {
    makeLine(0, i, canvas.width, i);
  }
  for(var j = 0; j <= canvas.width; j += val) {
    makeLine(j, 0, j, canvas.height);
  }
  ctx.stroke();
}

// draw it first to make it the background and only when it loads
backgroundImage.onload = function() {
  ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
  drawGrid(10, "blue");
  drawGrid(20, "red");
  drawGrid(40, "black");
}
canvas {
  border-radius: 3px;
  box-shadow: 1px 1px 10px blue;
}
<canvas width="320" height="200">

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

window.onload = function() {
  var canvas = document.querySelector("canvas"),
    ctx = canvas.getContext("2d"),
    backgroundImage = document.querySelector("#background-img");

  function makeLine(start_x, start_y, end_x, end_y) {
    ctx.moveTo(start_x, start_y);
    ctx.lineTo(end_x, end_y);
  }

  function drawGrid(val, color) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    for(var i = 0; i <= canvas.height; i += val) {
      makeLine(0, i, canvas.width, i);
    }
    for(var j = 0; j <= canvas.width; j += val) {
      makeLine(j, 0, j, canvas.height);
    }
    ctx.stroke();
  }

  // no need for the .onload since the code is executing after everything loads
  ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
  drawGrid(10, "blue");
  drawGrid(20, "red");
  drawGrid(40, "black");
}
canvas {
  border-radius: 3px;
  box-shadow: 1px 1px 10px blue;
}
.hidden {
  display: none;
}
<canvas width="320" height="200"></canvas>
<img id="background-img" class="hidden" src="https://openclipart.org/image/400px/svg_to_png/260587/Surreal-Fantastic-Nature.png" alt="nature painting">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...