1 回答

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
該CanvasRenderingContext2D.drawImage()
功能可以將多種類型的圖像作為源,包括另一個(gè) Canvas。下面的示例顯示圖像已加載到第一個(gè)畫布中。然后你可以通過按住鼠標(biāo)并移動(dòng)它來繪制它。當(dāng)您釋放時(shí),第二個(gè)畫布將繪制第一個(gè)畫布當(dāng)時(shí)的圖像。
所有的魔法都在最后一個(gè)函數(shù)中。
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>
添加回答
舉報(bào)