为了账号安全,请及时绑定邮箱和手机立即绑定

创建图像来绘制东西,然后在画布上绘制图像

创建图像来绘制东西,然后在画布上绘制图像

慕村9548890 2023-04-01 16:31:36
大家好!是否可以使用 JavaScript 创建图像然后在其上渲染形状,然后将其绘制到游戏画布上?无需使用 dataurl、url 或 src,就可以了!var ctx = document.getElementById("canvas").getContext("2d");var img = new Image();// TODO: Draw stuff to the image imgfunction game() {    window.requestAnimationFrame(game);    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);    ctx.drawImage(img, 0, 0, 256, 256);}window.requestAnimationFrame(game);
查看完整描述

1 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

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>


查看完整回答
反对 回复 2023-04-01
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信