如何写精华回答,获更多曝光?
发布
CanvasRenderingContext2D绘制刮刮卡特效动画的问题设置this.context.globalCompositeOperation = 'xor’时候随着手势的刮开 效果出现问题
代码如下:
import image from '@ohos.multimedia.image'
@Component
export struct FillStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
// private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)
@State x: number = 0
@State y: number = 0
@State x_left: number = 0
@State y_top: number = 0
@State iconVisible: boolean = false
build() {
Stack({ alignContent: Alignment.TopStart }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor(Color.Transparent)
.onReady(() => {
this.getPixmapFromMedia($r('app.media.test')).then((image) => {
this.context.drawImage(image, this.x, this.y)
})
this.context.lineWidth = 40
this.context.beginPath()
this.context.fillStyle = Color.Transparent
this.context.lineCap = 'round' //round square
this.context.globalCompositeOperation = 'xor' //xor
})
Image($r('app.media.icon'))
.width('30')
.height('30')
.margin({
left: this.x_left,
top: this.y_top
})
.visibility(this.iconVisible ? Visibility.Visible : Visibility.None)
}
.width('100%')
.height('100%')
.gesture(
PanGesture({ direction: PanDirection.All })
.onActionStart((event) => {
this.context?.moveTo(event.fingerList[0].localX, event.fingerList[0].localY)
})
.onActionUpdate((event) => {
this.iconVisible = true
this.x_left = event.fingerList[0].localX
this.y_top = event.fingerList[0].localY
this.context?.lineTo(this.x_left, this.y_top)
this.context?.stroke()
this.context?.restore()
})
.onActionEnd((event) => {
this.iconVisible = false
}))
}
private async getPixmapFromMedia(resource: Resource) {
let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({
bundleName: resource.bundleName,
moduleName: resource.moduleName,
id: resource.id
})
let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength))
let createPixelMap: image.PixelMap = await imageSource.createPixelMap({
desiredPixelFormat: image.PixelMapFormat.RGB_565,
desiredSize: {
width: 1080,
height: 1170
}
})
await imageSource.release()
return createPixelMap
}
}