[英]Javascript Canvas get data from image and display it
我不知道為什么這行不通。 圖像的src屬性隨新數據一起更改,但是該圖像實際上不可見。 我嘗試了幾種不同的圖像。 它只是瀏覽器中的javascript,並且需要Jquery。
<body>
<img src="" id="test">
</body>
<script>
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let img = new Image();
img.onload = getIt
img.src = 'download.png';
function getIt() {
canvas.width = this.width;
canvas.height = this.height;
const imageData = ctx.getImageData(0, 0, this.width, this.height);
ctx.drawImage(this, canvas.width , canvas.height);
ctx.putImageData(imageData, canvas.width, canvas.height);
$('#test').get(0).src = canvas.toDataURL("image/png");
}
</script>
我嘗試了幾種不同的圖像,都是png。 目前,這是該項目的全部代碼,因此我預見不到任何可能干擾該項目的代碼。
結果是這樣,但是看不到圖像:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAeCAYAAAAhDE4sAAAAMklEQVRIS+3SsQ0A....etc" id="test">
編輯:似乎它可能是不正確地從圖像中獲取數據,但我不知道為什么...我的意思是為什么它會獲取數據但不完整或不正確?
請嘗試以下操作:(您無需獲取或放置圖像數據)
您也正在這樣做: ctx.putImageData(imageData, canvas.width, canvas.height);
。 這意味着您要在畫布外部完全繪制圖像。 改為執行此操作: ctx.putImageData(imageData, 0,0);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let img = new Image();
img.onload = getIt
img.src = "download.png";
function getIt() {
canvas.width = this.width;
canvas.height = this.height;
//draw the image onto the canvas
ctx.drawImage(this, 0,0);
//use the data uri
test.src = canvas.toDataURL("image/png");
}
<img src="" id="test">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.