HTML5 Canvas 图像教程
要使用 Konva 创建图像,可以使用 Konva.Image() 对象。
有关完整的属性和方法列表,请参阅 Image API 参考。
- Vanilla
- React
- Vue
import Konva from 'konva';
const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight
});
const layer = new Konva.Layer();
stage.add(layer);
// main API:
const imageObj = new Image();
imageObj.onload = function () {
const yoda = new Konva.Image({
x: 50,
y: 50,
image: imageObj,
width: 106,
height: 118
});
layer.add(yoda);
};
imageObj.src = 'https://konvajs.org/assets/yoda.jpg';
// alternative API:
Konva.Image.fromURL('https://konvajs.org/assets/darth-vader.jpg', function (darthNode) {
darthNode.setAttrs({
x: 200,
y: 50,
scaleX: 0.5,
scaleY: 0.5,
cornerRadius: 20
});
layer.add(darthNode);
});
import { Stage, Layer, Image } from 'react-konva';
import { useEffect, useState } from 'react';
import useImage from 'use-image';
const App = () => {
const [yodaImage] = useImage('https://konvajs.org/assets/yoda.jpg');
const [vaderImage] = useImage('https://konvajs.org/assets/darth-vader.jpg');
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Image
x={50}
y={50}
image={yodaImage}
width={106}
height={118}
/>
<Image
x={200}
y={50}
image={vaderImage}
scaleX={0.5}
scaleY={0.5}
cornerRadius={20}
/>
</Layer>
</Stage>
);
};
export default App;
<template>
<v-stage :config="stageSize">
<v-layer>
<v-image
v-if="yodaImage"
:config="{
x: 50,
y: 50,
image: yodaImage,
width: 106,
height: 118
}"
/>
<v-image
v-if="vaderImage"
:config="{
x: 200,
y: 50,
image: vaderImage,
scaleX: 0.5,
scaleY: 0.5,
cornerRadius: 20
}"
/>
</v-layer>
</v-stage>
</template>
<script setup>
import { useImage } from 'vue-konva';
const stageSize = {
width: window.innerWidth,
height: window.innerHeight
};
const [yodaImage] = useImage('https://konvajs.org/assets/yoda.jpg');
const [vaderImage] = useImage('https://konvajs.org/assets/darth-vader.jpg');
</script>