gpt4 book ai didi

javascript - 如何使用 React Konva Image 将 Canvas 绘制回自身上?

转载 作者:行者123 更新时间:2023-12-02 22:51:36 39 4
gpt4 key购买 nike

我正在尝试实现 this Stack Overflow questions' top answerreact-konva 中,但停留在这行代码上:

  ctx.drawImage(canvas,
blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height,
blurredRect.x, blurredRect.y, blurredRect.width, blurredRect.height
);
  • 我们如何创建具有 9 个参数的 Image 组件?
  • 我们要向第二个 Image 组件添加哪个 canvas 元素以及如何添加?
// draft code
import useImage from 'use-image';

const [image] = useImage(url, "anonymous");

<Stage width={width} height={height}>
<Layer>
<Image image={image} width={width} height={height}></Image>
// second Image here with the blur?
<Rect fill="rgba(255,255,255,0.2)" x={80} y={80} width={200} height={200} />
</Layer>
</Stage>

最佳答案

您不需要使用<Rect>来自最初问题的组件,因为您只需创建 canvas 元素并将其用于 <Image>组件。

有很多方法可以做到这一点。这是如何使用钩子(Hook)来制作这样的 Canvas 的示例:

import React, { Component } from "react";
import { render } from "react-dom";
import { Stage, Layer, Image } from "react-konva";
import useImage from "use-image";

const useCanvas = () => {
const [image] = useImage(
"https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg"
);
const [canvas, setCanvas] = React.useState(null);

React.useEffect(() => {
// do this only when image is loaded
if (!image) {
return;
}
var blurredRect = {
x: 80,
y: 80,
height: 200,
width: 200,
spread: 10
};
const canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");

canvas.width = image.width / 2;
canvas.height = image.height / 2;
// first pass draw everything
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
// next drawings will be blurred
ctx.filter = "blur(" + blurredRect.spread + "px)";
// draw the canvas over itself, cropping to our required rect
ctx.drawImage(
canvas,
blurredRect.x,
blurredRect.y,
blurredRect.width,
blurredRect.height,
blurredRect.x,
blurredRect.y,
blurredRect.width,
blurredRect.height
);
// draw the coloring (white-ish) layer, without blur
ctx.filter = "none"; // remove filter
ctx.fillStyle = "rgba(255,255,255,0.2)";
ctx.fillRect(
blurredRect.x,
blurredRect.y,
blurredRect.width,
blurredRect.height
);

setCanvas(canvas);
}, [image]);

return canvas;
};

const App = () => {
const canvas = useCanvas();
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Image image={canvas} />
</Layer>
</Stage>
);
};

render(<App />, document.getElementById("root"));

https://codesandbox.io/s/react-konva-canvas-for-image-ypfmj

关于javascript - 如何使用 React Konva Image 将 Canvas 绘制回自身上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160383/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com