Javascript/HTML5使用图像填充画布

Javascript/HTML5 using image to fill canvas

本文关键字:填充 图像 HTML5 Javascript      更新时间:2023-09-26

我正在尝试获取图像来填充我的画布。这是我正在尝试的代码:

var blueprint_background = new Image();
blueprint_background.src = 'images/blueprint_background.png'; 
var pattern = context.createPattern(blueprint_background, "repeat");
context.fillStyle = pattern;
context.fill();

问题是什么都没有出现。我能够做基本的context.fillRect(..)示例,但这给我带来了麻烦。

谢谢。

您必须等到图像加载,使用图像的 onload 属性知道它何时加载。

var blueprint_background = new Image();
blueprint_background.src = 'images/blueprint_background.png'; 
blueprint_background.onload = function(){
    var pattern = context.createPattern(this, "repeat");
    context.fillStyle = pattern;
    context.fill();
};

如果有人想从 Worker 中的图像创建模式,请注意。

内部工人类图像未定义!

ReferenceError: Image is not defined

在这种情况下,我们可以执行以下操作:

const result = await fetch('./image.png');
const blob = await result.blob();
const image = await createImageBitmap(blob);
const pattern = canvasContext2D.createPattern(image, 'repeat');

然后只需填写OffscreenCanvasContext2D:

canvasContext2D.fillStyle = pattern;
canvasContext2D.fill();

引用:

  • 屏幕外画布 - developer.mozilla.org
  • OffscreenCanvasRenderingContext2D - html.spec.whatwg.org
  • 工人 - developer.mozilla.org
  • 获取 - developer.mozilla.org
  • 斑点 - developer.mozilla.org
  • 创建图像位图 - developer.mozilla.org
  • 创建模式 - html.spec.whatwg.org