possible to use html images like canvas with getIm

2020-07-03 06:43发布

I'd like to know if there is a way to dynamically modify/access the data contained in html images just as if they were an html5 canvas element. With canvas, you can in javascript access the raw pixel data with getImageData() and putImageData(), but I have thus far been not able to figure out how to do this with images.

7条回答
Deceive 欺骗
2楼-- · 2020-07-03 07:39

After having some issues with this code, I want to add one or two things to Phrogz's answer :

// 1) Create a canvas, either on the page or simply in code
var w = myImgElement.width, h=myImgElement.height; // NEw : you need to set the canvas size if you don't want bug with images that makes more than 300*150

var canvas = document.createElement('canvas');
canvas.height = h;
canvas.width = w;
var ctx    = canvas.getContext('2d');

// 2) Copy your image data into the canvas
var myImgElement = document.getElementById('foo');
ctx.drawImage( myImgElement, 0, 0, w, h ); // Just in case...

// 3) Read your image data
var imgdata = ctx.getImageData(0,0,w,h);
var rgba = imgdata.data;

// And then continue as in the other code !
查看更多
登录 后发表回答