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>
添加回答
举报