canvas----图片的像素同源操作

制作反色效果

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>Document</title>
		<style>
			body {
				background: #000000;
				color: #ffffff;
			}
			
			canvas {
				background: #ffffff;
				transition: translate 0.5s;
			}
		</style>
	</head>

	<body>

		<canvas id="canvas" width="600" height="400"></canvas>
	</body>
	<script>
		var oc = document.getElementById("canvas");
		var cvsCtx = oc.getContext("2d");
		var yImag = new Image()
		yImag.onload = function() {
			draw(this)
		}
		let oImg

		function draw(obj) {
			cvsCtx.width = obj.width
			cvsCtx.drawImage(yImag, 0, 0)
			oImg = cvsCtx.getImageData(0, 0, obj.width, obj.height)

			var w = oImg.width
			var h = oImg.height
			for(var i = 0; i < h; i++) {
				for(var j = 0; j < w; j++) {
					var result = []
					var color = getXY(oImg, j, i)
					result[0] = 255 - color[0]
					result[1] = 255 - color[1]
					result[2] = 255 - color[2]
					result[3] = 255  //这个不能减,减了就是透明的了

					setXY(oImg, j, i, result)
				}
			}
			console.log(oImg)
			cvsCtx.putImageData(oImg, 0, 0)

		}
		yImag.src = "abc.png"

		function getXY(obj, x, y) {
			let w = obj.width
			let h = obj.height
			let data = obj.data
			let arr = []
			arr[0] = data[(y * w + x) * 4]
			arr[1] = data[(y * w + x) * 4 + 1]
			arr[2] = data[(y * w + x) * 4 + 2]
			arr[3] = data[(y * w + x) * 4 + 3]
			return arr
		}

		function setXY(obj, x, y, color) {
			let w = obj.width
			let h = obj.height
			let data = obj.data
			data[(y * w + x) * 4] = color[0]
			data[(y * w + x) * 4 + 1] = color[1]
			data[(y * w + x) * 4 + 2] = color[2]
			data[(y * w + x) * 4 + 3] = color[3]
		}
	</script>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_41069726/article/details/89448236