HTML5 canvas 图像教程

要使用 Konva 创建图像,我们可以实例化一个 Konva.Image() 对象并设置 image 属性。

对于 image 属性,您可以使用:

  1. window.Image 的实例或 document.createElement('image')
  2. 画布元素
  3. 视频元素

有关属性和方法的完整列表,请查看 Konva.Image 文档

如果您想将 SVG 图像绘制到画布上,请查看 如何在画布上绘制 SVG 图像 的文章。

Konva Image Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Image Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
});

var layer = new Konva.Layer();
stage.add(layer);

// main API:
var imageObj = new Image();
imageObj.onload = function () {
var yoda = new Konva.Image({
x: 50,
y: 50,
image: imageObj,
width: 106,
height: 118,
});

// add the shape to the layer
layer.add(yoda);
};
imageObj.src = '/assets/yoda.jpg';

// alternative API:
Konva.Image.fromURL('/assets/darth-vader.jpg', function (darthNode) {
darthNode.setAttrs({
x: 200,
y: 50,
scaleX: 0.5,
scaleY: 0.5,
cornerRadius: 20,
});
layer.add(darthNode);
});
</script>
</body>
</html>