同样两张图片,对应同样的canvas大小(即图片本身大小),用H5 canvas获取到的数据与小程序内wx.canvasGetImageData获取到的数据有很大差距!(数组长度是相同的,但数据不同)
H5获取数据如下:
小程序获取数据如下:
目测是api处理数据有误差?望排查~
我也发现了,确切说是iOS是反转的,Android和模拟器下正常。
写了个简单的测试代码:
<!--pages/test/test.wxml--> < view > < canvas canvas-id = 'mycanvas' style = "width:20px; height: 20px;" ></ canvas > < text > color at (10, 5): {{color1}} color at (10, 15): {{color2}} </ text > </ view > |
// pages/test/test.js Page({ data: { color1: '' , color2: '' }, onLoad() { this .draw() setTimeout(() => { this .getImage() }, 1000) }, draw() { const ctx = wx.createCanvasContext( 'mycanvas' ) ctx.beginPath() ctx.rect(0, 0, 20, 10) ctx.setFillStyle( 'red' ) ctx.fill() ctx.closePath() // ctx.draw() ctx.beginPath() ctx.rect(0, 10, 20, 10) ctx.setFillStyle( 'blue' ) ctx.fill() ctx.closePath() ctx.draw() }, getImage() { const self = this wx.canvasGetImageData({ canvasId: 'mycanvas' , x: 0, y: 0, width: 20, height: 20, success(image) { console.log(image.data) self.setData({ color1: self.getColor(image, 10, 5), color2: self.getColor(image, 10, 15) }) }, fail(error) { console.error(error) } }) }, getColor(image, x, y) { const i = (x + image.width * y) * 4 const r = image.data[i + 0] const g = image.data[i + 1] const b = image.data[i + 2] const a = image.data[i + 3] return `rgba(${r}, ${g}, ${b}, ${a})` } }) |
简单讲,就是上面画了红色矩形,下方是蓝色。然后对上下两个位置去颜色值。
Android上取值正确,iOS上是反转的
手动实现了一下反转
// /utils/util.js
const concatArrayBuffer = (... arrays ) => {
let totalLength = 0 ;
for ( let arr of arrays ) {
totalLength += arr . length ;
}
let result = new Uint8ClampedArray ( totalLength );
let offset = 0 ;
for ( let arr of arrays ) {
result . set ( arr , offset );
offset += arr . length ;
}
return result ;
}
const revertImage = ( data , width , height ) => {
if (! data ) return data ;
let dataViews = [];
let len = width * 4 ;
for ( let i = 0 ; i < height ; i ++) {
let start = i * width * 4 ;
let newBuff = data . slice ( start , start + len );
dataViews . unshift ( newBuff );
}
let result = concatArrayBuffer (... dataViews );
return result . buffer ;
}
module . exports = {
revertImage
}
// /pages/XXXPage.js
wx . canvasGetImageData ({
canvasId: 'myCanvas' ,
x: 0 ,
y: 0 ,
width: width ,
height: height ,
success ( res ) {
wx . hideLoading ();
// 3. IOS图像反转
let buffer = res . data . buffer ;
try {
let systemInfo = wx . getSystemInfoSync ();
let platform = systemInfo . platform ;
if ( platform === 'ios' ) {
buffer = util . revertImage ( res . data , res . width , res . height );
}
} catch ( e ) {
}
......