首页 > 解决方案 > 如何使用反应原生画布?

问题描述

我想在本机反应中包含画布。我已经安装了https://https://www.npmjs.com/package/react-native-canvas并且它可以工作。

我想做这样的事情:

const canvasElem = document.getElementById("canvasElem");
const ctx = canvasElem.getContext('2d');
const clearBtn = document.getElementById('clearBtn');

ctx.strokeStyle = '#000000';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.lineWidth = 3;

let isDrawing = false;
let lastX = 0;
let lastY = 0;

function clearCanvas() {
  ctx.clearRect(0, 0, canvasElem.width, canvasElem.height);
}

function drawSignature(event) {
 if(!isDrawing) return;
ctx.beginPath();
//start from
ctx.moveTo(lastX, lastY);
//move to
ctx.lineTo(event.offsetX, event.offsetY) //value from event
ctx.stroke();


[lastX, lastY] = [event.offsetX, event.offsetY];
};

canvasElem.addEventListener('mousemove', drawSignature)
canvasElem.addEventListener('mousedown', (event) => {
  isDrawing = true;
  [lastX, lastY] = [event.offsetX, event.offsetY];

});
canvasElem.addEventListener('mouseup', () => isDrawing = false);
canvasElem.addEventListener('mouseout', () => isDrawing = false);

clearBtn.addEventListener('click', clearCanvas);

它在浏览器中工作。如何在 react native 中获取 event.offSetX 和 event offSetY 以及事件的等价物(mouseup、mousedown、mousemove 等)?

标签: react-native

解决方案


推荐阅读