【问题标题】:Creating image to draw stuff to it, Then draw the image over canvas创建图像以绘制东西,然后在画布上绘制图像
【发布时间】:2023-04-02 05:43:01
【问题描述】:

大家好!

是否可以使用 JavaScript 创建图像,然后在其上渲染形状,然后将其绘制到游戏画布上?

不使用 dataurl、url 或 src,在任何一个上!

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);

【问题讨论】:

  • 图像需要一个 src,一个 url 或一个 dataurl 并且加载后然后在画布上绘制
  • @PatrickEvans 假设它没有 src,我们不能在图像中添加内容,因为它是空的吗?
  • canvas 是一种图像。将您的图像绘制到另一个画布中,然后将该图像添加到“游戏画布”中。

标签: javascript image html5-canvas


【解决方案1】:

CanvasRenderingContext2D.drawImage() 函数可以将多种类型的图像作为源,包括另一个 Canvas。下面的示例显示图像已加载到第一个画布中。然后,您可以通过按住鼠标并移动它来绘制它。当您释放第二个画布时,将绘制第一个画布当时的图像。

所有的魔法都在最后一个函数中。

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>

【讨论】:

  • 谢谢!根据你的回答,我可以做空图像并告诉第一个画布从 url 使用它,然后继续你说的!
猜你喜欢
  • 2017-08-07
  • 2021-07-08
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 1970-01-01
  • 2013-10-28
  • 2013-11-07
  • 1970-01-01
相关资源
最近更新 更多