效果图
const SignName: FC<SignNameProps> = ({ dispatch, SignName }) => {
const router = useRouter()
const { SignNameInfo } = SignName
const [Ctx, setCtx] = useState<any>(null)
const [isButtonDown, setButtonDown] = useState<boolean>(false);
const [dpr,] = useState<any>(Taro.getSystemInfoSync().pixelRatio);
const [screen, setScreen] = useState<any>({
screenWidth: '',
screenHeight: ''
})
useEffect(() => {
console.log(Taro.getSystemInfoSync().windowHeight);
Taro.getSystemInfo({
success: function (res) {
console.log(res)
setScreen({
screenWidth: res.windowWidth,
screenHeight: res.windowHeight - 50
})
}
})
setTimeout(() => {
initCanvas()
}, 500)
}, [])
useReady(() => {
/在useeffect 中使用无法获取节点
initCanvas()
})
const initCanvas = () => {
Taro.createSelectorQuery()
.select('#canvas')
.fields({
node: true,
size: true,
})
.exec((res) => {
setButtonDown(false)
const width = res[0].width
const height = res[0].height
const canvas = res[0].node
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, width, height)//清空画布
ctx.beginPath()//开始绘制
ctx.fillStyle = '#ffffff'//设置背景色
ctx.fillRect(0, 0, width, height)
for (let i = 0; i < 20; i++) {
ctx.rotate((-45 * Math.PI) / 180); // 水印初始偏转角度
ctx.font = "16px Arial";
ctx.fillStyle = "#EEEFEF";
ctx.fillText("日照港南区操作表 日照港南区操作表 日照港南区操作表 日照港南区操作表 日照港南区操作表 日照港南区操作表 ", -200, i * 60);
ctx.rotate((45 * Math.PI) / 180); // 把水印偏转角度调整为原来的,不然他会一直转
}
setCtx(ctx)
})
}
const move = (event: any) => {
Ctx.lineTo(event.changedTouches[0].x, event.changedTouches[0].y)
Ctx.strokeStyle = '#000000';
Ctx.lineWidth = 2;
Ctx.lineCap = 'round';
Ctx.lineJoin = 'round';
Ctx.stroke();
Ctx.draw = false;
}
const TouchStart = (event) => {
Ctx.beginPath()
Ctx.moveTo(event.changedTouches[0].x, event.changedTouches[0].y)
setButtonDown(true)
}
const canvasEnd = () => {
Ctx.closePath();
setButtonDown(false)
}
const convertCanvasToImage = () => {
let image: any
Taro.createSelectorQuery()
.select('#canvas')
.fields({
node: true,
size: true,
})
.exec((res) => {
const canvas = res[0].node
image = canvas.toDataURL("image/png");
console.log(image);
})
return image;
}
return (
<View className='SignNamePage'>
<View className="canvas">
<Canvas type="2d" onTouchStart={TouchStart} onTouchMove={move} style={`width: 100%; height: 240px;`} canvasId="canvas" id='canvas'>
</Canvas>
</View>
<View className="caozuo">
<View className="initCanvas" onClick={initCanvas}>清空</View>
<View className="initCanvas" onClick={convertCanvasToImage}>完成</View>
</View>
</View>
)
}