[英]Loading an image onto a canvas with javaScript
大家好,我目前正在測試使用 canvas 元素繪制所有背景(我稍后會為這些圖像添加效果,這也是我不使用 css 加載圖像的原因),也就是說我目前在加載圖像時遇到困難到畫布上。 這是代碼:
<html>
<head>
<title>Canvas image testing</title>
<script type="text/javascript">
function Test1() {
var ctx = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
//Loading of the home test image - img1
var img1 = new Image();
img1.src = 'img/Home.jpg';
//drawing of the test image - img1
img1.onload = function () {
//draw background image
ctx.drawimage(img1, 0, 0);
//draw a box over the top
ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
ctx.fillRect(0, 0, 500, 500);
};
}
}
</script>
<style type="text/css">
canvas { border: 2px solid black; width: 100%; height: 98%; }
</style>
</head>
<body onload="Test1();">
<canvas id="canvas" width="1280" height="720"></canvas>
</body>
</html>
我認為我沒有正確加載圖像,但我不確定。
有幾件事:
drawimage
應該是drawImage
- 注意大寫的 i。getElementById
正在尋找 ID 為canvas
的元素,但它應該是test1
。 canvas
是標簽,而不是 ID。ctx
替換canvas
變量(例如在canvas.getContext
行中),因為這是您用來選擇畫布元素的變量。src
之前綁定您的onload
處理程序。所以你的函數應該是這樣的:
function Test1() {
var ctx = document.getElementById('test1');
if (ctx.getContext) {
ctx = ctx.getContext('2d');
//Loading of the home test image - img1
var img1 = new Image();
//drawing of the test image - img1
img1.onload = function () {
//draw background image
ctx.drawImage(img1, 0, 0);
//draw a box over the top
ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
ctx.fillRect(0, 0, 500, 500);
};
img1.src = 'img/Home.jpg';
}
}
使用較新的 JavaScript 功能:
let img = await loadImage("./my/image/path.jpg");
ctx.drawImage(img, 0, 0);
loadImage
函數如下所示:
function loadImage(url) {
return new Promise(r => { let i = new Image(); i.onload = (() => r(i)); i.src = url; });
}
在為圖像設置 src 之前將 onload 事件偵聽器移動到。
var img1 = new Image();
//drawing of the test image - img1
img1.onload = function () {
//draw background image
ctx.drawImage(img1, 0, 0);
//draw a box over the top
ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
ctx.fillRect(0, 0, 500, 500);
};
img1.src = 'img/Home.jpg';
將您的本地文件資源 (url) 分配給圖像源並使用您要加載的畫布中的上下文繪制圖像。 而已。 請參閱下面的代碼。
var loadImage = function (url, ctx) {
var img = new Image();
img.src = url
img.onload = function () {
ctx.drawImage(img, 0, 0);
}
}
var c = document.getElementById("canvas"); var ctx = var ctx = c.getContext("2d"); var img1 = new Image(); //drawing of the test image - img1 img1.onload = function () { //draw background image ctx.drawImage(img1, 0, 0); //draw a box over the top ctx.fillStyle = "rgba(200, 0, 0, 0.5)"; ctx.fillRect(0, 0, 500, 500); }; img1.src = 'img/Home.jpg';
<canvas id="canvas"></canvas
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.