我如何为画布设置默认图片?

问题描述 投票:-1回答:1

我有一张PNG图片(在我的数据库中),我想把它加载到我的页面的画布中。我不知道怎么做。我不知道如何将图片加载为一个ImageBitmap或任何与canvas兼容的东西。我如何给canvas提供字节,并告诉它使用png格式集mime为png?

javascript html canvas
1个回答
1
投票

我会把它分成两部分。(1) 你要把图像加载到ImageBitmap可以使用的东西里 (2) 你要创建ImageBitmap把它放到你的画布里。

这可能看起来像这样。

const fileName = 'resources/image.png';
const fetched = await fetch(fileName); // Retrieve an image file.
const blob = await fetched.blob(); // Get a blob to represent this image.

const imageBitmap = await createImageBitmap(blob); // Create an imageBitmap from this blob.
const canvas = document.getElementById('canvas'); // Make sure your HTML contains a <canvas> element.
const context = canvas.getContext('2d');

context.drawImage(imageBitmap, 0,0); // Draw this image onto the canvas.


0
投票

HTML

<img id="myImage" src="imageSrc">
<canvas id ="myCanvas" width="width" height="height"></canvas>

JS

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("myImage");
ctx.drawImage(img, 0, 0);

这是最简单的方法。的 drawImage() 方法可以接受多个图片源,而不仅仅是一个HTML图片元素。例如,你不需要像我演示的那样把图片放在DOM中。我建议你阅读文档。https:/developer.mozilla.orgen-USdocsWebAPICanvasRenderingContext2DdrawImage。

© www.soinside.com 2019 - 2024. All rights reserved.