猿问

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

大家好!

是否可以使用 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);


慕村9548890
浏览 121回答 1
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>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答