canvas实现图片镜像翻转的2种方式
原文引用:https://www.qetool.com/scripts/view/23387.html
1. 通过canvas自带的画布方法进行翻转
var img = new Image(); //这个就是 img标签的dom对象 img.src = './sy.png'; img.onload = function () { //图片加载完成后,执行此方法 ctx.drawImage(img, posx, posy, 210, 80); };
play.addEventListener('click', function () { ctx.clearRect(0, 0, canvas.width, canvas.height);//清除画布 //位移来做镜像翻转 ctx.translate(210+ posx * 2, 0); ctx.scale(-1, 1); //左右镜像翻转 //ctx.translate(0, 160 + posy * 2); //ctx.scale(1, -1); //上下镜像翻转 ctx.drawImage(img, 0, 0, 210, 80); });
2.像素点的镜像翻转方法
//竖向像素反转 function imageDataVRevert(sourceData, newData) { for (var i = 0, h = sourceData.height; i < h; i++) { for (var j = 0, w = sourceData.width; j < w; j++) { newData.data[i * w * 4 + j * 4 + 0] = sourceData.data[(h - i) * w * 4 + j * 4 + 0]; newData.data[i * w * 4 + j * 4 + 1] = sourceData.data[(h - i) * w * 4 + j * 4 + 1]; newData.data[i * w * 4 + j * 4 + 2] = sourceData.data[(h - i) * w * 4 + j * 4 + 2]; newData.data[i * w * 4 + j * 4 + 3] = sourceData.data[(h - i) * w * 4 + j * 4 + 3]; } } return newData; }
//横向像素反转 function imageDataHRevert(sourceData, newData) { for (var i = 0, h = sourceData.height; i < h; i++) { for (j = 0, w = sourceData.width; j < w; j++) { newData.data[i * w * 4 + j * 4 + 0] = sourceData.data[i * w * 4 + (w - j) * 4 + 0]; newData.data[i * w * 4 + j * 4 + 1] = sourceData.data[i * w * 4 + (w - j) * 4 + 1]; newData.data[i * w * 4 + j * 4 + 2] = sourceData.data[i * w * 4 + (w - j) * 4 + 2]; newData.data[i * w * 4 + j * 4 + 3] = sourceData.data[i * w * 4 + (w - j) * 4 + 3]; } } return newData; } `` var img = new Image(); //这个就是 img标签的dom对象 img.src = './sy.png'; img.onload = function () { //图片加载完成后,执行此方法 ctx.drawImage(img, 0, 0, 210, 80); }; //像素点操作 var imgData = ctx.getImageData(0, 0, 210, 80); var newImgData = ctx.getImageData(0, 0, 210, 80); // var newImgData = ctx.getImageData(0, 0, w, h); ctx.putImageData(imageDataVRevert(newImgData, imgData), 0, 0); //上下翻转 // ctx.putImageData(imageDataHRevert(newImgData, imgData), 0, 0);//左右翻转~~~~
标签:canvas,img,ctx,newData,var,镜像,data,sourceData,翻转 From: https://www.cnblogs.com/yaosusu/p/17295416.html