Rabios
Rabios

Reputation: 77

Creating image to draw stuff to it, Then draw the image over canvas

Hello everyone!

Is it possible to create image with JavaScript then render shapes on it, Then draw it to the game canvas?

Without using dataurl, url, or src, on any of that!

var ctx = document.getElementById("canvas").getContext("2d");
var img = new Image();
// TODO: Draw stuff to the image img

function game() {
    window.requestAnimationFrame(game);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    ctx.drawImage(img, 0, 0, 256, 256);
}

window.requestAnimationFrame(game);

Upvotes: 0

Views: 83

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

The CanvasRenderingContext2D.drawImage() function can take an multiple types of images as a source, including another Canvas. The example below shows that an image is loaded in the first canvas. Then you can draw on it by holding down the mouse and moving it. When you release the second canvas will draw an image of the first canvas as it is at that moment.

And all the magic is just in the last function.

contextTwo.drawImage(canvasOne, 0, 0, 256, 256);

const canvasOne = document.getElementById('canvas1');
const canvasTwo = document.getElementById('canvas2');
const contextOne = canvasOne.getContext('2d');
const contextTwo = canvasTwo.getContext('2d');

canvasOne.width = 256;
canvasOne.height = 256;

canvasTwo.width = 256;
canvasTwo.height = 256;

const canvasBounds = canvasOne.getBoundingClientRect();

let mouseData = {
  isClicked: false,
  position: [0, 0],
}

const onMouseDown = event => {
  mouseData.isClicked = true;
  render();
};

const onMouseMove = ({ clientX, clientY }) => {
  const x = clientX - canvasBounds.left;
  const y = clientY - canvasBounds.top;
  mouseData.position = [x, y];
  render();
};

const onMouseUp = event => {
  mouseData.isClicked = false;
  render();
  moveImage();
};

function setup() {
  const img = new Image();
  img.src = '//picsum.photos/256/256'
  img.onload = function() {
    contextOne.drawImage(img, 0, 0, 256, 256);
  }
  
  canvasOne.addEventListener('mousedown', onMouseDown);
  canvasOne.addEventListener('mousemove', onMouseMove);
  canvasOne.addEventListener('mouseup', onMouseUp);
}

function render() {
  requestAnimationFrame(() => {
    const { isClicked, position } = mouseData;
    const [ x, y ] = position;
    if (isClicked) {
      contextOne.beginPath();
      contextOne.arc(x, y, 5, 0, Math.PI * 2)
      contextOne.fillStyle = 'red'
      contextOne.fill();
      contextOne.closePath();
    }
  });
}

function moveImage() {
  contextTwo.drawImage(canvasOne, 0, 0, 256, 256);
}

setup();
body {
  display: flex;
}

canvas {
  width: 256px;
  height: 256px;
  border: 1px solid #d0d0d0;
}
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

Upvotes: 1

Related Questions